创建C#属性以禁止方法执行

时间:2013-05-29 18:46:18

标签: c# reflection custom-attributes methodinfo

我希望创建一个自定义属性来禁止在C#中执行Method,即使它被调用也是如此。 例如,如果方法有' Skip'即使从Main调用它也不应该执行它。

public class MyClass {

  public static void main()
  {
    aMethod();  
  }

  [Skip]
  public void aMethod() {
    ..
  }

}

如何使用C#中的反射来实现这一目标?


在下面的代码片段中,我设法提取了带有跳过属性的方法,我只是无法弄清楚如何停止执行它们!

MethodInfo[] methodInfos = typeof (MyClass).GetMethods();

foreach (var methodInfo in methodInfos)
{
  if (methodInfo.HasAttribute(typeof(SkipAttribute)))
  {
    // What goes here ??
  }
}

非常欢迎任何有正确方向的帮助或建议:)

2 个答案:

答案 0 :(得分:5)

目前尚不清楚你在追求什么。

首先,@Ignore用于告诉JUnit测试运行器忽略测试。你没有在你的问题中提到测试,但我们应该清楚这是@Ignore的用途。 .NET中的测试运行器具有类似的属性(例如,在xUnit中,属性为[Ignore])。

因此,如果您正在使用测试运行器,请找到该测试运行器的相应属性。如果您没有使用测试运行器,那么您认为@Ignore仅与测试运行有密切关系后到底是什么?

你在编写自己的测试跑步者吗?为什么?有plentyreally good免费测试版可用。使用它们!

  

我希望该属性即使调用方法也禁止执行。

嗯,如果我看过一个,那就是代码味道。

您有几个选择。

将代码插入到您应用[Ignore]每个方法中:

[AttributeUsage(AttributeTargets.Method)]
public class Ignore : Attribute { }

[Ignore]
public static void M() {
    var ignoreAttributes =
        MethodBase.GetCurrentMethod().GetCustomAttributes(typeof(Ignore), true);
    if (ignoreAttributes.Any()) {
        return;
    }
    // method execution proceeds
    // do something
}

或者,您可以使用interception technique

或者,您可以使用post-compilation框架。

所有这些都有非常严重的问题。他们有问题,因为你正在做的是代码味道。

答案 1 :(得分:0)

不太确定你到底想要达到什么目的 如果你的目的是创建像JUnit / NUnit这样的东西,那么下面是演示这些工具如何做的代码:

MethodInfo[] methodInfos = typeof (MyClass).GetMethods();

foreach (var methodInfo in methodInfos)
{
  bool ignore = methodInfo.HasAttribute(typeof(SkipAttribute));
  if (ignore)
  {
    // do nothing
  }
  else
  {
     // launch method
     methodInfo.Invoke(/*params here*/);
  }
}

但是如果你想让CLR调用方法,即使有明确的调用 - 那么你需要使用Preprocessor Directives