簡體   English   中英

通過屬性值查找類屬性

[英]Find class property by Attribute value

我想通過其屬性和屬性值找到一個類屬性。

給定此屬性和類:

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”。

以古老的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
}

你也可以做這樣的事情

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM