c# - 如何知道为类型定义的属性?

标签 c# .net reflection attributes

我定义了一个自定义属性并将其添加到几个类中。知道我正在使用反射来捕获程序集中的所有类型。我只想过滤掉定义了该属性的类型。

我见过 Type 对象的 Attributes 属性,但它只返回 specific enum 中包含的值.

如何检索定义了自定义属性的类型?

最佳答案

你可以这样做:

object[] attributes = typeof(SomeType).GetCustomAttributes(typeof(YourAttribute), true);

但我更喜欢使用自定义扩展方法:

public static class ReflectionExtensions
{
    public static TAttribute GetAttribute<TAttribute>(this ICustomAttributeProvider obj, bool inherit)
        where TAttribute : Attribute
    {
        return obj.GetAttributes<TAttribute>(inherit).FirstOrDefault();
    }

    public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this ICustomAttributeProvider obj, bool inherit)
        where TAttribute : Attribute
    {
        return obj.GetCustomAttributes(typeof (TAttribute), inherit).Cast<TAttribute>();
    }

    public static bool HasAttribute<TAttribute>(this ICustomAttributeProvider obj, bool inherit)
        where TAttribute : Attribute
    {
        return obj.GetAttributes<TAttribute>(inherit).Any();
    }
}

(它们也适用于程序集、方法、属性等,而不仅仅是类型)

关于c# - 如何知道为类型定义的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12091900/

相关文章:

c# - ASP.NET 5.0 MVC6 的 Omnisharp sublime 文本错误

c# - 大型集合初始值设定项启动时的 Stackoverflow

c# - 使用反射获取所有具有 Serializable 属性的扩展类型

java - 传递方法作为参数并收到错误 : java. lang.NoSuchMethodException:

c# - 如何使用 WPF 数据绑定(bind)来编辑多个项目的公共(public)字段

c# - 为什么某些字 rune 字会导致 Java 中的语法错误?

c# - 开源 CMS(.Net 与 Java)

c# - 如何在 C# 中从 StreamReader 获取文本

.net - ILMerge 在合并时挂起

ios - swift 。通过字符串名称引用实例变量