代码之家  ›  专栏  ›  技术社区  ›  me.at.coding

使用通过Expression提供的属性名称访问对象的属性[重复]

  •  0
  • me.at.coding  · 技术社区  · 2 年前

    我正在尝试实现 Data transformation using Reflection 1. 我的代码中的示例。

    这个 GetSourceValue 函数有一个比较各种类型的开关,但我想删除这些类型和属性 GetSourceValue 只使用一个字符串作为参数来获取属性的值。我想在字符串中传递一个类和属性,并解析该属性的值。

    这可能吗?

    1. Web Archive version of original blog post

    0 回复  |  直到 3 年前
        1
  •  2
  •   pasx    3 年前
     public static object GetPropValue(object src, string propName)
     {
         return src.GetType().GetProperty(propName).GetValue(src, null);
     }
    

    当然,你会想添加验证之类的东西,但这就是它的要点。

        2
  •  1
  •   Jeff Codes    7 年前

    这样的怎么样:

    public static Object GetPropValue(this Object obj, String name) {
        foreach (String part in name.Split('.')) {
            if (obj == null) { return null; }
    
            Type type = obj.GetType();
            PropertyInfo info = type.GetProperty(part);
            if (info == null) { return null; }
    
            obj = info.GetValue(obj, null);
        }
        return obj;
    }
    
    public static T GetPropValue<T>(this Object obj, String name) {
        Object retval = GetPropValue(obj, name);
        if (retval == null) { return default(T); }
    
        // throws InvalidCastException if types are incompatible
        return (T) retval;
    }
    

    这将允许您使用单个字符串进入属性,如下所示:

    DateTime now = DateTime.Now;
    int min = GetPropValue<int>(now, "TimeOfDay.Minutes");
    int hrs = now.GetPropValue<int>("TimeOfDay.Hours");
    

    您可以将这些方法用作静态方法或扩展。

        3
  •  0
  •   Mohammad Sadeq Sirjani    3 年前

    添加到任何 Class :

    public class Foo
    {
        public object this[string propertyName]
        {
            get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
            set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
        }
    
        public string Bar { get; set; }
    }
    

    然后,您可以使用作为:

    Foo f = new Foo();
    // Set
    f["Bar"] = "asdf";
    // Get
    string s = (string)f["Bar"];