Dictionary mapping strings to properties

后端 未结 2 495
粉色の甜心
粉色の甜心 2020-12-21 13:14

I have a class where I would like to return the value of various properties based on a string that I can define as an attribute like so:

    [FieldName(\"dat         


        
2条回答
  •  有刺的猬
    2020-12-21 13:35

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

    private static readonly IDictionary> PropertyMap;
    

    Then you need your static initializer to be

    static MyClass()
    {
        PropertyMap = new Dictionary>();
    
        var myType = typeof(ArisingViewModel);
    
        foreach (var propertyInfo in myType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            if (propertyInfo.GetGetMethod() != null)
            {
                var attr = propertyInfo.GetCustomAttribute();
    
                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 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 {
    
      private static readonly IDictionary> PropertyMap;
    
    
      static MyClass()
      {
        PropertyMap = new Dictionary>();
    
        var myType = typeof(T);
    
        foreach (var propertyInfo in myType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            if (propertyInfo.GetGetMethod() != null)
            {
                var attr = propertyInfo.GetCustomAttribute();
    
                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 prop;
        if (PropertyMap.TryGetValue(field, out prop)) {
           return prop(obj);
        }
        return null; //Return null if no match
      }
    }
    

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

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

提交回复
热议问题