gpt4 book ai didi

c# - 如何获取具有给定属性的属性列表?

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:14 24 4
gpt4 key购买 nike

我有一个类型 t,我想获取具有属性 MyAttribute 的公共(public)属性的列表。该属性用 AllowMultiple = false 标记,如下所示:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]

目前我有的是这个,但我认为有更好的方法:

foreach (PropertyInfo prop in t.GetProperties())
{
object[] attributes = prop.GetCustomAttributes(typeof(MyAttribute), true);
if (attributes.Length == 1)
{
//Property with my custom attribute
}
}

我该如何改进?如果这是重复的,我很抱歉,那里有大量的反射线程......这似乎是一个非常热门的话题。

最佳答案

var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

这避免了必须具体化任何属性实例(即它比 GetCustomAttribute[s]() 更便宜。

关于c# - 如何获取具有给定属性的属性列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43393981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com