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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/987982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:59:46  来源:igfitidea点击:

How can I get the value of a string property via Reflection?

c#stringreflectionproperties

提问by Alan

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

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

如何通过反射获取字符串属性 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
}

It seems that my problem is that the property is an indexer type, with a System.String.

看来我的问题是该属性是一个索引器类型,带有 System.String。

Also, how do I tell if the property is an indexer?

另外,如何判断该属性是否为索引器?

采纳答案by Jake

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

关于后续问题:索引器将始终命名为 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)*/});
}

回答by Jake Pearson

Foo f = new Foo();
f.Bar = "Jon Skeet is god.";

foreach(var property in f.GetType().GetProperties())
{
    if(property.Name != "Bar")
    {
         continue;
    }
    object o = property.GetValue(f,null); //throws exception TargetParameterCountException for String type
}

And here is for the followup:

这是后续行动:

class Test
{
    public class Foo
    {
        Dictionary<string, int> data =new Dictionary<string,int>();
        public int this[string index]
        {
            get { return data[index]; }
            set { data[index] = value; }
        }

        public Foo()
        {
            data["a"] = 1;
            data["b"] = 2;
        }
    }

    public Test()
    {
        var foo = new Foo();
        var property = foo.GetType().GetProperty("Item");
        var value = (int)property.GetValue(foo, new object[] { "a" });
        int i = 0;
    }
}

回答by em70

I couldn't reproduce the issue. Are you sure you're not trying to do this on some object with indexer properties? In that case the error you're experiencing would be thrown while processing the Item property. Also, you could do this:

我无法重现该问题。您确定不是要在具有索引器属性的对象上执行此操作吗?在这种情况下,在处理 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");

回答by Handcraftsman

Foo f = new Foo();
f.Bar = "x";

string value = (string)f.GetType().GetProperty("Bar").GetValue(f, null);

回答by JP Alioto

var val = f.GetType().GetProperty("Bar").GetValue(f, null);

回答by Stan R.

PropertyInfo propInfo = f.GetType().GetProperty("Bar");
object[] obRetVal = new Object[0];
string bar = propInfo.GetValue(f,obRetVal) as string;

回答by Chris Cherwin

the getvalue with object and null worked great for me. Thanks for the posts.

带有 object 和 null 的 getvalue 对我来说非常有用。谢谢你的帖子。

Context: Looping through all properties in an MVC model for New Hires and determining their form posted values:

上下文:循环遍历新员工的 MVC 模型中的所有属性并确定它们的表单发布值:

newHire => the Model, with many properties, whose posted form values I want to write individually to a set of database records

newHire => 具有许多属性的模型,我想将其发布的表单值单独写入一组数据库记录

foreach(var propertyValue in newHire.GetProperties())
{
string propName = propertyValue.Name;

string postedValue = newHire.GetType().GetProperty(propName).GetValue(newHire, null).ToString();

}

回答by Ali

Its easy to get property value of any objectby use Extension method like:

使用扩展方法可以轻松获取任何对象的属性值,例如:

public static class Helper
    {
        public static object GetPropertyValue(this object T, string PropName)
        {
            return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null);
        }
    }

Usage is:

用法是:

Foo f = new Foo();
f.Bar = "x";
var balbal = f.GetPropertyValue("Bar");

回答by Sayed Muhammad Idrees

To get the property names of the object by just passing the object you can use this function may this works.

要通过传递对象来获取对象的属性名称,您可以使用此函数可能会起作用。

just make object object a class and pass into it.

只需使对象对象成为一个类并传入它。

 public void getObjectNamesAndValue(object obj)
    {
        Type type = obj.GetType();
        BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
        PropertyInfo[] prop = type.GetProperties(flags);
        foreach (var pro in prop)
        {
            System.Windows.Forms.MessageBox.Show("Name :" + pro.Name + " Value : "+  pro.GetValue(obj, null).ToString());
        }

    }

But this will only work when the object properties are "Public"

但这仅在对象属性为“公共”时才有效