【问题标题】:Find class property by Attribute value按属性值查找类属性
【发布时间】:2018-08-04 02:18:20
【问题描述】:

我想通过它的属性和属性值找到一个类属性。

给定这个属性和类:

class MyAttribute : Attribute
{
    public MyAttribute(string name)
    {
        Name = name;
    }

    public string Name { get; set; }
}


class MyClass
{
    [MyAttribute("Something1")]
    public string Id { get; set; }

    [MyAttribute("Something2")]
    public string Description { get; set; } 
}

我知道我可以找到这样的特定属性:

var c = new MyClass();
var props = c.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

但是如何过滤属性名称值“Something2”?

所以我的最终目标是通过在 MyClass 中搜索值为“Something”的属性 MyAttribute 来输出“MyClass.Description”。

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    你也可以这样做

    var c = new MyClass();
    var props = c.GetType()
                 .GetProperties()
                 .Where(prop => prop.GetCustomAttributes(false)
                                    .OfType<MyAttribute>()
                                    .Any(att => att.Name == "Something1"));
    

    【讨论】:

    • 请注意,GetCustomAttributes的参数是是否搜索继承的属性。对于属性,该值被忽略。如果您需要在继承层次结构(例如抽象属性)中执行此操作,则必须使用 Attribute.GetCustomAttributes
    【解决方案2】:

    在旧的 foreach 风格中

    var c = new MyClass();
    var props = c.GetType().GetProperties()
        .Where(prop => Attribute.IsDefined(prop, typeof(MyAttribute)));
    
    foreach (var prop in props)
    {
        MyAttribute myAttr = (MyAttribute)Attribute.GetCustomAttribute(prop, typeof(MyAttribute));
        if (myAttr.Name == "Something2")
            break; //you got it
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多