【问题标题】:How to get a property value based on the name如何根据名称获取属性值
【发布时间】:2011-07-27 08:31:03
【问题描述】:

有没有办法根据对象的名称获取对象属性的值?

例如,如果我有:

public class Car : Vehicle
{
   public string Make { get; set; }
}

var car = new Car { Make="Ford" };

我想编写一个方法,我可以在其中传递属性名称并返回属性值。即:

public string GetPropertyValue(string propertyName)
{
   return the value of the property;
}

【问题讨论】:

    标签: c# asp.net reflection


    【解决方案1】:
    return car.GetType().GetProperty(propertyName).GetValue(car, null);
    

    【讨论】:

    • 请记住,由于它使用反射,因此速度要慢得多。可能不是问题,但需要注意。
    • "无法从 String 转换为 BindingFlags"
    • 有没有“更快”的方式@MattGreer?
    【解决方案2】:

    你必须使用反射

    public object GetPropertyValue(object car, string propertyName)
    {
       return car.GetType().GetProperties()
          .Single(pi => pi.Name == propertyName)
          .GetValue(car, null);
    }
    

    如果你想要真正的花哨,你可以把它做成一个扩展方法:

    public static object GetPropertyValue(this object car, string propertyName)
    {
       return car.GetType().GetProperties()
          .Single(pi => pi.Name == propertyName)
          .GetValue(car, null);
    }
    

    然后:

    string makeValue = (string)car.GetPropertyValue("Make");
    

    【讨论】:

    • 我也可以为 SetValue 执行此操作吗?怎么样?
    • 小事-扩展方法可能不需要名为car的变量
    • 要了解如何根据 propertyName 字符串设置属性值,请在此处查看答案:Setting the value of properties via reflection
    【解决方案3】:

    你想要反射

    Type t = typeof(Car);
    PropertyInfo prop = t.GetProperty("Make");
    if(null != prop)
    return prop.GetValue(this, null);
    

    【讨论】:

    • +1 这是显示所有中间对象的最佳答案
    • 我可以传递索引并获取属性名称和值,而不是传递属性值(这样我就可以遍历所有属性)?
    • @singhswat 您应该将其作为一个新问题提出。
    【解决方案4】:

    除了其他人回答,它很容易通过使用扩展方法获取任何对象的属性值,例如:

    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);
            }
    
        }
    

    用法是:

    Car foo = new Car();
    var balbal = foo.GetPropertyValue("Make");
    

    【讨论】:

    • 从 C#6 开始,您可以使用空传播 return T.GetType().GetProperty(PropName)?.GetValue(T, null);
    【解决方案5】:

    扩展 Adam Rackis 的答案 - 我们可以像这样简单地使扩展方法通用:

    public static TResult GetPropertyValue<TResult>(this object t, string propertyName)
    {
        object val = t.GetType().GetProperties().Single(pi => pi.Name == propertyName).GetValue(t, null);
        return (TResult)val;
    }
    

    如果你愿意,你也可以抛出一些错误处理。

    【讨论】:

      【解决方案6】:

      简单示例(无需在客户端编写反射硬代码)

      class Customer
      {
          public string CustomerName { get; set; }
          public string Address { get; set; }
          // approach here
          public string GetPropertyValue(string propertyName)
          {
              try
              {
                  return this.GetType().GetProperty(propertyName).GetValue(this, null) as string;
              }
              catch { return null; }
          }
      }
      //use sample
      static void Main(string[] args)
          {
              var customer = new Customer { CustomerName = "Harvey Triana", Address = "Something..." };
              Console.WriteLine(customer.GetPropertyValue("CustomerName"));
          }
      

      【讨论】:

        【解决方案7】:

        为了避免反射,您可以设置一个字典,其中您的属性名称作为字典值部分中的键和函数,从您请求的属性中返回相应的值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-26
          • 1970-01-01
          相关资源
          最近更新 更多