【问题标题】:Use reflection to get the value of a property by name in a class instance使用反射在类实例中按名称获取属性的值
【发布时间】:2011-06-21 19:32:13
【问题描述】:

假设我有

class Person
{
    public Person(int age, string name)
    {
        Age = age;
        Name = name; 
    }
    public int Age{get;set}
    public string Name{get;set}
}

我想创建一个方法来接受一个字符串,该字符串包含 "age" 或 "name" 并返回具有该属性值的对象。

像下面的伪代码:

    public object GetVal(string propName)
    {
        return <propName>.value;  
    }

如何使用反射来做到这一点?

我正在使用 asp.net 3.5、c# 3.5 进行编码

【问题讨论】:

  • 问问自己,强类型访问是否是更好的选择。大多数时候都是这种情况。
  • 请记住,您显示的类没有具有任何属性。它有两个字段。字段和属性之间有很大的不同——你真正感兴趣的是什么?
  • @ChaosPandion:强类型访问是什么意思?开关(道具名称){} ?
  • @jon - 实际上是属性。让我编辑我的问题。
  • @TheMoot - 请记住,我的建议非常笼统,因为我不知道您的程序的逻辑。这可能意味着对现有逻辑的完全重写,这在许多情况下是不可行的。

标签: c# asp.net reflection


【解决方案1】:

我认为这是正确的语法...

var myPropInfo = myType.GetProperty("MyProperty");
var myValue = myPropInfo.GetValue(myInstance, null);

【讨论】:

  • 我没有编辑权限,但是你的第二行 var myValue = propertyInfo.GetValue(myInstance, null);应该说 myproperty.Info 等。谢谢,然后它起作用了。
【解决方案2】:

首先,您提供的示例没有属性。它有私有成员变量。对于属性,您将有如下内容:

public class Person
{
    public int Age { get; private set; }
    public string Name { get; private set; }

    public Person(int age, string name)
    {
        Age = age;
        Name = name;
    }
}

然后使用反射来获取值:

 public object GetVal(string propName)
 {
     var type = this.GetType();
     var propInfo = type.GetProperty(propName, BindingFlags.Instance);
     if(propInfo == null)
         throw new ArgumentException(String.Format(
             "{0} is not a valid property of type: {1}",
             propName, 
             type.FullName));

     return propInfo.GetValue(this);
 }

但请记住,由于您已经可以访问该类及其属性(因为您也可以访问该方法),因此仅使用属性而不是通过反射做一些花哨的事情要容易得多。

【讨论】:

  • 对不起,乔恩指出了这一点。我编辑了我的例子。我把这个例子简化了一点。
  • 示例代码假定缺少的属性和值为null 的属性是等价的。如果给定的 propName 未映射到属性,您可能需要抛出 ArgumentException
【解决方案3】:

你可以这样做:

Person p = new Person( 10, "test" );

IEnumerable<FieldInfo> fields = typeof( Person ).GetFields( BindingFlags.NonPublic | BindingFlags.Instance );

string name = ( string ) fields.Single( f => f.Name.Equals( "name" ) ).GetValue( p );
int age = ( int ) fields.Single( f => f.Name.Equals( "age" ) ).GetValue( p );

请记住,因为这些是私有实例字段,您需要显式声明绑定标志才能通过反射获取它们。

编辑:

您似乎将示例从使用字段更改为属性,所以我将把它留在这里,以防您再次更改。 :)

【讨论】:

  • 我编辑了我的示例,因为我已经傻了一点。但是你的回答可能对领域有用,所以谢谢,我会投票给你。
【解决方案4】:

ClassInstance.GetType.GetProperties() 将为您提供您的 PropertyInfo 对象列表。 旋转检查 PropertyInfo.Name 与 propName 的 PropertyInfos。如果它们相等,则调用 PropertyInfo 类的 GetValue 方法来获取它的值。

http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多