Quel est le moyen le plus court d’affirmer qu’un attribut est appliqué à la méthode en c #?

StackOverflow https://stackoverflow.com/questions/639913

Question

Quel est le moyen le plus rapide d'affirmer qu'un attribut est appliqué à la méthode en c #?

J'utilise nunit-2.5

:

Était-ce utile?

La solution

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

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

Autres conseils

Je ne suis pas sûr de la méthode d'assert utilisée par nunit, mais vous pouvez simplement utiliser cette expression booléenne pour le paramètre qui lui est transmis (en supposant que vous puissiez utiliser LINQ:

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

Si l'attribut est appliqué, il retournera la valeur true.

Si vous souhaitez créer une version générique (sans utiliser typeof), vous pouvez utiliser une méthode générique pour le faire à votre place:

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

Et appelez-le dans votre méthode d'assertion comme ceci:

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

Pour ce faire avec une expression, vous pouvez d'abord définir la méthode d'extension suivante:

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)));
}

Et appelez-le dans le code comme ceci:

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

Notez que les paramètres transmis à la méthode importent peu, car la méthode n'est jamais appelée, elle a simplement besoin de l'expression.

Une alternative à nunit 2.5:

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

Assert.That(methodInfo, Has.Attribute(typeof(MyAttribute)));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top