public class Foo
{
public string Bar {get; set;}
}
如何通过反射获取字符串属性 Bar 的值?如果 PropertyInfo 类型是 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。
另外,如何判断该属性是否为索引器?
最佳答案
您可以通过名称获取属性:
Foo f = new Foo();
f.Bar = "Jon Skeet is god.";
var barProperty = f.GetType().GetProperty("Bar");
string s = barProperty.GetValue(f,null) as string;
关于后续问题: 索引器将始终命名为 Item 并在 getter 上有参数。 所以
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)*/});
}
关于c# - 如何通过反射获取字符串属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/987982/