我想通過其屬性和屬性值查找類屬性。鑒于此屬性和類: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”?所以我的最終目標(biāo)是通過在 MyClass 中搜索值為“Something”的屬性 MyAttribute 來輸出“MyClass.Description”。
2 回答

呼喚遠(yuǎn)方
TA貢獻(xiàn)1856條經(jīng)驗 獲得超11個贊
你也可以做這樣的事情
var c = new MyClass();var props = c.GetType() .GetProperties() .Where(prop => prop.GetCustomAttributes(false) .OfType<MyAttribute>() .Any(att => att.Name == "Something1"));

牧羊人nacy
TA貢獻(xiàn)1862條經(jīng)驗 獲得超7個贊
以舊的 foreach 風(fēng)格
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
}
- 2 回答
- 0 關(guān)注
- 156 瀏覽
添加回答
舉報
0/150
提交
取消