2017-01-05 7 views
-1

Можно ли обобщить решение для работы для любого типа?Как утверждать, что метод имеет указанный атрибут

Существует замечательный solution утверждению, существует ли заданный атрибут по методу:

public static MethodInfo MethodOf(Expression<System.Action> expression) 
{ 
    MethodCallExpression body = (MethodCallExpression)expression.Body; 
    return body.Method; 
} 

public static bool MethodHasAuthorizeAttribute(Expression<System.Action> expression) 
{ 
    var method = MethodOf(expression); 

    const bool includeInherited = false; 
    return method.GetCustomAttributes(typeof(AuthorizeAttribute), includeInherited).Any(); 
} 

Использование было бы что-то вроде этого:

 var sut = new SystemUnderTest(); 
     var y = MethodHasAuthorizeAttribute(() => sut.myMethod()); 
     Assert.That(y); 

Как мы обобщим это решение и изменить подпись с:

public static bool MethodHasAuthorizeAttribute(Expression<System.Action> expression) 

на что-то вроде этого:

public static bool MethodHasSpecifiedAttribute(Expression<System.Action> expression, Type specifiedAttribute) 

Можно ли обобщить решение работать для любого типа?

ответ

1
public static MethodInfo MethodOf(Expression<Action> expression) 
{ 
    MethodCallExpression body = (MethodCallExpression)expression.Body; 
    return body.Method; 
} 

public static bool MethodHasAttribute(Expression<Action> expression, Type attributeType) 
{ 
    var method = MethodOf(expression); 

    const bool includeInherited = false; 
    return method.GetCustomAttributes(attributeType, includeInherited).Any(); 
} 

Или с обобщениями:

public static bool MethodHasAttribute<TAttribute>(Expression<Action> expression) 
    where TAttribute : Attribute 
{ 
    var method = MethodOf(expression); 

    const bool includeInherited = false; 
    return method.GetCustomAttributes(typeof(TAttribute), includeInherited).Any(); 
} 

Что вы назвали бы так:

var sut = new SystemUnderTest(); 
y = MethodHasAttribute<AuthorizeAttribute>(() => sut.myMethod()); 
That(y);