且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

字典将字符串映射到属性

更新时间:2022-03-27 00:20:47

您将需要更改字典定义,以便函数可以接受该类的实例

you will need to change your dictionary definition so that the function will accept an instance of the class

private static readonly IDictionary<string, Func<ArisingViewModel,string>> PropertyMap;

然后,您需要使用静态初始值设定项

Then you need your static initializer to be

static MyClass()
{
    PropertyMap = new Dictionary<string, Func<ArisingViewModel,string>>();

    var myType = typeof(ArisingViewModel);

    foreach (var propertyInfo in myType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
    {
        if (propertyInfo.GetGetMethod() != null)
        {
            var attr = propertyInfo.GetCustomAttribute<FieldNameAttribute>();

            if (attr == null)
                continue;

            PropertyInfo info = propertyInfo;
            PropertyMap.Add(attr.FieldName, obj => (string)info.GetValue(obj,null));
        }
    }
}

public static object GetPropertyValue(ArisingViewModel obj, string field)
{
    Func<ArisingViewModel,string> prop;
    if (PropertyMap.TryGetValue(field, out prop)) {
       return prop(obj);
    }
    return null; //Return null if no match
  }

您还可以使解决方案更多

You can also make your solution a little more generic if you wish.

public static MyClass<T> {

  private static readonly IDictionary<string, Func<T,string>> PropertyMap;


  static MyClass()
  {
    PropertyMap = new Dictionary<string, Func<T,string>>();

    var myType = typeof(T);

    foreach (var propertyInfo in myType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
    {
        if (propertyInfo.GetGetMethod() != null)
        {
            var attr = propertyInfo.GetCustomAttribute<FieldNameAttribute>();

            if (attr == null)
                continue;

            PropertyInfo info = propertyInfo;
            PropertyMap.Add(attr.FieldName, obj => (string)info.GetValue(obj,null));
        }
    }
  }

  public static object GetPropertyValue(T obj, string field)
  {
    Func<ArisingViewModel,string> prop;
    if (PropertyMap.TryGetValue(field, out prop)) {
       return prop(obj);
    }
    return null; //Return null if no match
  }
}

EDIT-和调用您将要使用的通用版本

EDIT -- and to call the generic version you would do

var value = MyClass<ArisingViewModel>.GetPropertyValue(mymodel,"data_bus");