c# - 如何通过反射获取字符串属性的值?

标签 c# string reflection properties

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/

相关文章:

c# - MySQL Lighter 版本的不错选择

javascript - 将对象从 Angularjs 传递到 MVC Controller 并映射到类对象

java - 如何逐行打印字符串对象

C# 对象编辑和序列化初始化

c# - LINQ to Entities 对具有嵌套对象的 Union 的空引用

c# - 将 "TOP 1"添加到 sql 语句是否会显着提高性能?

c++ - 如何增加 QString 中的字符 (Qt)

java - 文本查询匹配(棘手)

c++ - 我可以获得正式而非实际模板参数的字符串表示形式吗?

java - 兼容反射的设计模式