memberInfo.GetValue() C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/115418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 14:25:34  来源:igfitidea点击:

memberInfo.GetValue() C#

提问by Boris Callens

How to get an instance's member's values?

如何获取实例成员的值?

With propertyInfos there is a propertyInfo.GetValue(instance, index), but no such thing exists in memberInfo.

使用 propertyInfos 有一个propertyInfo.GetValue(instance, index),但在 memberInfo 中不存在这样的东西。

I searched the net, but it seems to stop at getting the member's name and type.

我在网上搜索,但它似乎停止获取成员的姓名和类型。

采纳答案by Matt Howells

I think what you need is FieldInfo.

我认为你需要的是FieldInfo.

回答by Carlo V. Dango

You have to downcast to FieldInfoor PropertyInfo:

你必须向下转型FieldInfoPropertyInfo

switch (memberInfo)
{
  case FieldInfo fieldInfo:
    return fieldInfo.GetValue(obj);
  case PropertyInfo propertyInfo:
    return propertyInfo.GetValue(obj);
  default:
    throw new InvalidOperationException();
}