简体   繁体   English

断言将属性应用于c#中的方法的最短方法是什么?

[英]Whats the shortest way to assert that an attribute is applied to method in c#?

Whats the shortest way to assert that an attribute is applied to method in c#? 断言将属性应用于c#中的方法的最短方法是什么?

I'm using nunit-2.5 我正在使用nunit-2.5

:) :)

MethodInfo mi = typeof(MyType).GetMethod("methodname");    

Assert.IsFalse (Attribute.IsDefined (mi, typeof(MyAttributeClass)));

I'm not sure of the assert method that nunit uses, but you can simply use this boolean expression for the parameter that is passed to it (assuming you are able to use LINQ: 我不确定nunit使用的assert方法,但是您可以简单地将此布尔表达式用作传递给它的参数(假设您可以使用LINQ:

methodInfo.GetCustomAttributes(attributeType, true).Any()

If the attribute is applied, then it will return true. 如果应用了该属性,则它将返回true。

If you want to make a generic version (and not use typeof) you can use a generic method to do this for you: 如果要创建通用版本(而不使用typeof),则可以使用通用方法为您执行此操作:

static bool IsAttributeAppliedToMethodInfo<T>(this MethodInfo methodInfo) 
    where T : Attribute
{
    // If the attribute exists, then return true.
   return methodInfo.GetCustomAttributes(typeof(T), true).Any();
}

And then call it in your assert method like so: 然后在您的assert方法中调用它,如下所示:

<assert method>(methodInfo.IsAttributeAppliedToMethodInfo<MyAttribute>());

To do this with an expression, you can define the following extension method first: 为此,您可以先定义以下扩展方法:

public static MethodInfo 
    AssertAttributeAppliedToMethod<TExpression, TAttribute>
    (this Expression<T> expression) where TAttribute : Attribute
{
    // Get the method info in the expression of T.
    MethodInfo mi = (expression.Body as MethodCallExpression).Method;

    Assert.That(mi, Has.Attribute(typeof(TAttribute)));
}

And then call it in code like this: 然后在这样的代码中调用它:

(() => Console.WriteLine("Hello nurse")).
    AssertAttributeAppliedToMethod<MyAttribute>();

Note that it doesn't matter what the parameters that are passed to the method are, as the method is never called, it simply needs the expression. 请注意,传递给该方法的参数是什么都没有关系,因为从不调用该方法,它只需要表达式。

An alternative for nunit 2.5: nunit 2.5的替代方法:

var methodInfo = typeof(MyType).GetMethod("myMethod");

Assert.That(methodInfo, Has.Attribute(typeof(MyAttribute)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM