c# - 从 property 属性获取数据

标签 c# reflection attributes

我有一个使用自定义属性的 View 模型,例如

public int Id { get; set; }
public string Name { get; set; }
[IsEnumeration(typeof(CaseStatus))]
public string Status { get; set; }

IsEnumeration 是一个自定义属性,它将 Enumeration 父类(super class)作为参数(实际上它可以接受任何类型,但这并不重要,因为没有其他人会使用它)

public class IsEnumerationAttribute : Attribute
{
    public Type Enumeration;
    public IsEnumerationAttribute(Type enumeration)
    {
        Enumeration = enumeration;
    }
}

我想要的是能够获得为任何参数指定的类型。目前我的代码如下所示:

    public T EnumerationValuesToDisplayNames<T>(T item) where T : new()
    {
        if (LoggedInUser.IsSuper) return item;
        var tProps = typeof (T).GetProperties()
            .Where(prop => Attribute
                 .IsDefined(prop, typeof (IsEnumerationAttribute)));

        foreach (var prop in tProps)
        {
            if (prop.GetValue(item, null) != null)
            {
                /*

    Here I look through all properties with the IsEnumerable attribute.
    I want to do something such as:
                var type = prop.GetAttribute(item, typeof(IsEnumerable));
                var displayName = Enumeration<type>.FromId(prop.GetValue(item, null));
                prop.SetValue(item, displayName);

                */
            }
        }
        return item;
    }

我希望这是有道理的,任何帮助将不胜感激,谢谢

最佳答案

假设从您的帖子中您定义了一个类:

public class Enumeration<T> {

  public static string FromId(string id) {
    // FromId Implmentation
  }

}

那么你应该只需要

foreach (var prop in tProps) {  
  var id=prop.GetValue(item, null);
  if (id!=null) {  
    var type = prop.GetCustomAttributes(typeof(EnumerationAttribute>,true).OfType<EnumerationAttribute>().Select(x=>x.Enumeration).First();
    var enumerationType=typeof(Enumeration<>).MakeGenericType(type);
    var fromIdMethod=enumerationType.GetMethod("FromId",BindingFlags.Public|BindingFlags.Static|BindingFlags.InvokeMethod);
    var displayName=fromIdMethod.Invoke(null,new object[] {id});
    prop.SetValue(item, displayName);  
  }  
}  

或者,您可以直接在 EnumerationAttribute 中实现 FromId 方法,然后您可以像这样直接调用它...

foreach (var prop in tProps) {  
  var id=prop.GetValue(item, null);
  if (id!=null) {  
    var enumAttrib = prop.GetCustomAttributes(typeof(EnumerationAttribute>,true).OfType<EnumerationAttribute>().First();
    var displayName=enumAttrib.FromId((string)id);
    prop.SetValue(item, displayName);  
  }  

关于c# - 从 property 属性获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7390061/

相关文章:

c# - 将 DateTime.Now 与确切时间进行比较

c# - 使用反射转换为通用类型对象

c# - 方法参数 C#

javascript - 如何使用 jQuery 获取图像 ID?

html - 脚本和样式元素的 HTML "nonce"属性的用途是什么?

c# - 在 web api 中使用多个自定义操作路由配置

c# - 使用 DateTime.TryParseExact 解析非标准日期格式

c# - 如何选择与对象列表中的属性值共享属性值的所有对象?

c# - 使用反射和锁定正确实例化分配给私有(private)静态 volatile 变量的类

class - 对象、属性、变量和类实例之间的区别