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

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

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


当前回答

没有快速检索属性的方法。但是代码应该是这样的(来源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
}

其他回答

没有快速检索属性的方法。但是代码应该是这样的(来源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
}

这是一个很老的问题,但我用过

我的方法有这个参数,但它可以建立:

Expression<Func<TModel, TValue>> expression

然后在这个方法中:

System.Linq.Expressions.MemberExpression memberExpression 
       = expression.Body as System.Linq.Expressions.MemberExpression;
Boolean hasIdentityAttr = System.Attribute
       .IsDefined(memberExpression.Member, typeof(IsIdentity));

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

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

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

您可以使用属性。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();

如果你试图在一个可移植类库PCL中做到这一点(像我一样),那么这里是你可以做到的方法:)

public class Foo
{
   public string A {get;set;}

   [Special]
   public string B {get;set;}   
}

var type = typeof(Foo);

var specialProperties = type.GetRuntimeProperties()
     .Where(pi => pi.PropertyType == typeof (string) 
      && pi.GetCustomAttributes<Special>(true).Any());

然后,如果需要,您可以检查具有此特殊属性的属性的数量。