C#用于检查属性的扩展方法

And*_*son 13 c# tdd extension-methods

对不起,如果这是一个愚蠢的菜鸟问题,请温柔地对待我,我正在努力学习......

我想测试模型和控制器之类的属性方法.主要是为了确保他们有正确的属性,即必需.但我也将它用作扩展方法和Lambdas的实验.

我想要的是一种方法,当被赋予某种东西时,它就像是一种东西

Controller controller = new Controller();
controller.MethodName(params).HasAttribute<AttributeName>();
Run Code Online (Sandbox Code Playgroud)

我已经尝试了一些扩展方法,但没有达到这个程度.我确信这应该很简单,但似乎无法使我的泛型等正确.

Ste*_*ven 19

也许你正在寻找这个:

Controller controller = new Controller();
bool ok = controller.GetMethod(c => c.MethodName(null, null))
    .HasAttribute<AttributeName>();
Run Code Online (Sandbox Code Playgroud)

像这样编写它的好处是你有完全编译时间支持.到目前为止,所有其他解决方案都使用字符串文字来定义方法.

以下是GetMethodHasAttribute<T>扩展方法的实现:

public static MethodInfo GetMethod<T>(this T instance,
    Expression<Func<T, object>> methodSelector)
{
    // Note: this is a bit simplistic implementation. It will
    // not work for all expressions.
    return ((MethodCallExpression)methodSelector.Body).Method;
}

public static MethodInfo GetMethod<T>(this T instance,
    Expression<Action<T>> methodSelector)
{
    return ((MethodCallExpression)methodSelector.Body).Method;
}

public static bool HasAttribute<TAttribute>(
    this MemberInfo member) 
    where TAttribute : Attribute
{
    return GetAttributes<TAttribute>(member).Length > 0;
}

public static TAttribute[] GetAttributes<TAttribute>(
    this MemberInfo member) 
    where TAttribute : Attribute
{
    var attributes = 
        member.GetCustomAttributes(typeof(TAttribute), true);

    return (TAttribute[])attributes;
}
Run Code Online (Sandbox Code Playgroud)