如何通过反射获取字符串属性的值? [英] How can I get the value of a string property via Reflection?

查看:25
本文介绍了如何通过反射获取字符串属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Foo
{
   public string Bar {get; set;}
}

如何通过反射获取字符串属性 Bar 的值?如果 PropertyInfo 类型为 System.String

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;

关于后续问题:索引器将始终命名为 Item 并在 getter 上有参数.所以

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆