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

    [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();

其他回答

如果你试图在一个可移植类库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());

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

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

这现在可以在没有表达式树和扩展方法的情况下以类型安全的方式完成,使用新的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();

如果你正在使用。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”来避免这种情况。