Create C # attribute to suppress method execution

I want to create a custom attribute that prohibits the execution of a method in C #, even if it is called. For example, in the code block below, if a method has the Skip attribute, it should not be executed, even if it is called from Main.

public class MyClass { public static void main() { aMethod(); } [Skip] public void aMethod() { .. } } 

How can I achieve this using reflection in C #?


In the code snippet below, I managed to extract the methods that carry the skip attribute, I just can’t figure out how to stop them from executing!

 MethodInfo[] methodInfos = typeof (MyClass).GetMethods(); foreach (var methodInfo in methodInfos) { if (methodInfo.HasAttribute(typeof(SkipAttribute))) { // What goes here ?? } } 

Any kind help or suggestion in the right direction is welcome :)

+4
source share
2 answers

It is not clear what you need.

Firstly, @Ignore means that the JUnit tester ignores the test. You did not mention testing in your question, but it should be clear to us that @Ignore exists for this. Test testers in .NET have similar attributes (for example, in xUnit, the [Ignore] attribute).

So, if you are using a test runner, find the appropriate attribute for this test runner. If you are not using a test runner, what exactly did you indicate after that that @Ignore is native only to test work?

Do you write your own test runner? What for? many really > good affordable test runners. Use them!

I want the attribute to suppress execution, even if the method is called .

Well that smell of code if I ever saw it.

You have several options.

Paste the code in each method that you apply [Ignore] to:

 [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 } 

Or you can use the interception method.

Or you can use the framework after compilation .

ALL of them have very serious problems. They have problems because what you do is the smell of code.

+4
source

Not quite sure what exactly you want to achieve.
If you intend to create something like JUnit / NUnit, then here is the code demonstrating how these tools work:

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

But if you want the method not to be called by the CLR, even if there is an explicit call, then you need to use Preprocessor Directives .

0
source

Source: https://habr.com/ru/post/1483426/


All Articles