给定一个类中的属性,带有属性—确定它是否包含给定属性的最快方法是什么?例如:

    [IsNotNullable]
    [IsPK]
    [IsIdentity]
    [SequenceNameAttribute("Id")]
    public Int32 Id
    {
        get
        {
            return _Id;
        }
        set
        {
            _Id = value;
        }
    }

例如,确定它具有“IsIdentity”属性的最快方法是什么?


当前回答

您可以使用属性。IsDefined方法

https://msdn.microsoft.com/en-us/library/system.attribute.isdefined (v = vs.110) . aspx

if(Attribute.IsDefined(YourProperty,typeof(YourAttribute)))
{
    //Conditional execution...
}

你可以提供你特别寻找的属性,或者你可以使用反射遍历所有的属性,就像这样:

PropertyInfo[] props = typeof(YourClass).GetProperties();

其他回答

您可以使用一个通用的(通用的)方法来读取给定MemberInfo的属性

public static bool TryGetAttribute<T>(MemberInfo memberInfo, out T customAttribute) where T: Attribute {
                var attributes = memberInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault();
                if (attributes == null) {
                    customAttribute = null;
                    return false;
                }
                customAttribute = (T)attributes;
                return true;
            }

您可以使用属性。IsDefined方法

https://msdn.microsoft.com/en-us/library/system.attribute.isdefined (v = vs.110) . aspx

if(Attribute.IsDefined(YourProperty,typeof(YourAttribute)))
{
    //Conditional execution...
}

你可以提供你特别寻找的属性,或者你可以使用反射遍历所有的属性,就像这样:

PropertyInfo[] props = typeof(YourClass).GetProperties();

这现在可以在没有表达式树和扩展方法的情况下以类型安全的方式完成,使用新的c#特性名称of(),如下所示:

Attribute.IsDefined(typeof(YourClass).GetProperty(nameof(YourClass.Id)), typeof(IsIdentity));

nameof()是在c# 6中引入的

如果你正在使用。net 3.5,你可以尝试使用表达式树。它比反思更安全:

class CustomAttribute : Attribute { }

class Program
{
    [Custom]
    public int Id { get; set; }

    static void Main()
    {
        Expression<Func<Program, int>> expression = p => p.Id;
        var memberExpression = (MemberExpression)expression.Body;
        bool hasCustomAttribute = memberExpression
            .Member
            .GetCustomAttributes(typeof(CustomAttribute), false).Length > 0;
    }
}

这更安全,因为它绑定到属性Id本身。如果属性名称更改,则在编译时失败。

而反射被绑定到字符串“Id”,如果属性名称发生变化,它不会编译失败,只会在执行该代码时失败。 现代版本的c#可以通过使用name (MyClass.Id)来代替“Id”来避免这种情况。

没有快速检索属性的方法。但是代码应该是这样的(来源Aaronaught):

var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity));

如果您需要检索属性属性,那么

var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false);
if (attr.Length > 0) {
    // Use attr[0], you'll need foreach on attr if MultiUse is true
}