Check if property has attribute

前端 未结 8 1546
刺人心
刺人心 2020-11-28 03:03

Given a property in a class, with attributes - what is the fastest way to determine if it contains a given attribute? For example:

    [IsNotNullable]
    [I         


        
8条回答
  •  再見小時候
    2020-11-28 03:36

    This can now be done without expression trees and extension methods in a type safe manner with the new C# feature nameof() like this:

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

    nameof() was introduced in C# 6

提交回复
热议问题