속성에 속성이 있는지 확인
속성이있는 클래스의 속성이 주어지면 주어진 속성이 포함되어 있는지 확인하는 가장 빠른 방법은 무엇입니까? 예를 들면 다음과 같습니다.
[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
}
.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;
}
}
공통 (일반) 방법을 사용하여 지정된 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;
}
@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();
}
}
}
Your test is then reduced to two lines
var property = PropertyHelper<MyClass>.GetProperty(x => x.MyProperty);
Attribute.IsDefined(property, typeof(MyPropertyAttribute));
If you are trying to do that in a Portable Class Library PCL (like me), then here is how you can do it :)
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());
You can then check on the number of properties that have this special property if you need to.
You can use the Attribute.IsDefined method
https://msdn.microsoft.com/en-us/library/system.attribute.isdefined(v=vs.110).aspx
if(Attribute.IsDefined(YourProperty,typeof(YourAttribute)))
{
//Conditional execution...
}
You could provide the property you're specifically looking for or you could iterate through all of them using reflection, something like:
PropertyInfo[] props = typeof(YourClass).GetProperties();
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
This is a pretty old question but I used
My method has this parameter but it could be built:
Expression<Func<TModel, TValue>> expression
Then in the method this:
System.Linq.Expressions.MemberExpression memberExpression
= expression.Body as System.Linq.Expressions.MemberExpression;
Boolean hasIdentityAttr = System.Attribute
.IsDefined(memberExpression.Member, typeof(IsIdentity));
참고URL : https://stackoverflow.com/questions/2051065/check-if-property-has-attribute
'development' 카테고리의 다른 글
Python 웹 프레임 워크, WSGI 및 CGI가 어떻게 결합 되는가 (0) | 2020.06.13 |
---|---|
테이블 행 수 (0) | 2020.06.13 |
약속을 관찰 가능으로 변환 (0) | 2020.06.13 |
다른 목차 C #에 목차 내용 추가 (0) | 2020.06.13 |
java.lang.NoClassDefFoundError : 클래스 XXX를 초기화 할 수 없습니다 (0) | 2020.06.13 |