给定一个类中的属性,带有属性—确定它是否包含给定属性的最快方法是什么?例如:
[IsNotNullable]
[IsPK]
[IsIdentity]
[SequenceNameAttribute("Id")]
public Int32 Id
{
get
{
return _Id;
}
set
{
_Id = value;
}
}
例如,确定它具有“IsIdentity”属性的最快方法是什么?
为了更新和/或增强@Hans Passant的答案,我将把属性的检索分离到一个扩展方法中。这有一个额外的好处,就是在GetProperty()方法中删除讨厌的魔法字符串。
public static class PropertyHelper<T>
{
public static PropertyInfo GetProperty<TValue>(
Expression<Func<T, TValue>> selector)
{
Expression body = selector;
if (body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
return (PropertyInfo)((MemberExpression)body).Member;
default:
throw new InvalidOperationException();
}
}
}
然后,您的测试被缩减为两行
var property = PropertyHelper<MyClass>.GetProperty(x => x.MyProperty);
Attribute.IsDefined(property, typeof(MyPropertyAttribute));
没有快速检索属性的方法。但是代码应该是这样的(来源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
}
您可以使用属性。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();