Ala*_*lan 20 c# string reflection properties
public class Foo
{
public string Bar {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
如何通过反射获得字符串属性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
}
Run Code Online (Sandbox Code Playgroud)
看来我的问题是该属性是一个索引器类型,带有System.String.
另外,如何判断该属性是否为索引器?
Jak*_*ake 47
您可以按名称获取酒店:
Foo f = new Foo();
f.Bar = "Jon Skeet is god.";
var barProperty = f.GetType().GetProperty("Bar");
string s = barProperty.GetValue(f,null) as string;
Run Code Online (Sandbox Code Playgroud)
关于后续问题: 索引器将始终命名为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)*/});
}
Run Code Online (Sandbox Code Playgroud)
我无法重现这个问题.你确定你没有尝试使用索引器属性在某个对象上执行此操作吗?在这种情况下,处理Item属性时会抛出您遇到的错误.此外,你可以这样做:
public static T GetPropertyValue<T>(object o, string propertyName)
{
return (T)o.GetType().GetProperty(propertyName).GetValue(o, null);
}
...somewhere else in your code...
GetPropertyValue<string>(f, "Bar");
Run Code Online (Sandbox Code Playgroud)