C# 如何使用反射获取属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10338018/
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
How to get a property value using reflection
提问by Icemanind
I have the following code:
我有以下代码:
FieldInfo[] fieldInfos;
fieldInfos = GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
What I am trying to do is get the value of one of my properties of the current instantiated instance at runtime using reflection. How can I do this?
我想要做的是在运行时使用反射获取当前实例化实例的属性之一的值。我怎样才能做到这一点?
采纳答案by James Johnson
Something like this should work:
这样的事情应该工作:
var value = (string)GetType().GetProperty("SomeProperty").GetValue(this, null);
回答by David Yaw
Try the GetPropertiesmethod, it should get you the property, instead of fields.
尝试GetProperties方法,它应该为您提供属性,而不是字段。
To retrieve the value, do something like this:
要检索该值,请执行以下操作:
object foo = ...;
object propertyValue = foo.GetType().GetProperty("PropertyName").GetValue(foo, null);
This is using GetProperty, which returns just one PropertyInfo object, rather than an array of them. We then call GetValue, which takes a parameter of the object to retrieve the value from (the PropertyInfo is specific to the type, not the instance). The second parameter to GetValue is an array of indexers, for index properties, and I'm assuming the property you're interested in isn't an indexed property. (An indexed property is what lets you do list[14]to retrieve the 14th element of a list.)
这是使用 GetProperty,它只返回一个 PropertyInfo 对象,而不是它们的数组。然后我们调用 GetValue,它接受对象的一个参数来从中检索值(PropertyInfo 特定于类型,而不是实例)。GetValue 的第二个参数是索引器数组,用于索引属性,我假设您感兴趣的属性不是索引属性。(索引属性可让您list[14]检索列表的第 14 个元素。)

