代码之家  ›  专栏  ›  技术社区  ›  Jenny

按属性值查找类属性

  •  1
  • Jenny  · 技术社区  · 7 年前

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

    给定此属性和类:

    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”的属性my attribute来输出“MyClass.Description”。

    2 回复  |  直到 7 年前
        1
  •  2
  •   hiram acebo    7 年前

    你也可以这样做

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

    以古老的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
    }
    
    推荐文章