我怎样才能得到通过反射的字符串属性的值? [英] How can I get the value of a string property via Reflection?
本文介绍了我怎样才能得到通过反射的字符串属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class Foo
{
public string Bar {get; set;}
}
我如何获得酒吧,一个字符串属性的值,通过反射?如果的PropertyInfo类型是System.String设置以下code会抛出异常。
How do I get the value of Bar, a string property, via reflection? The following code will throw an exception if the PropertyInfo type is a System.String
Foo f = new Foo();
f.Bar = "Jon Skeet is god.";
foreach(var property in f.GetType().GetProperties())
{
object o = property.GetValue(f,null); //throws exception TargetParameterCountException for String type
}
看来,我的问题是,属性是一个索引器型,以System.String。
It seems that my problem is that the property is an indexer type, with a System.String.
另外,我怎么知道如果该属性是一个索引?
Also, how do I tell if the property is an indexer?
推荐答案
您可以仅仅通过名称获得属性:
You can just get the property by name:
Foo f = new Foo();
f.Bar = "Jon Skeet is god.";
var barProperty = f.GetType().GetProperty("Bar");
string s = barProperty.GetValue(f,null) as string;
关于跟进的问题:
索引器将永远被命名项目,并且对吸气参数。
因此,
Regarding the follow up question: Indexers will always be named Item and have arguments on the getter. So
Foo f = new Foo();
f.Bar = "Jon Skeet is god.";
var barProperty = f.GetType().GetProperty("Item");
if (barProperty.GetGetMethod().GetParameters().Length>0)
{
object value = barProperty.GetValue(f,new []{1/* indexer value(s)*/});
}
这篇关于我怎样才能得到通过反射的字符串属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文