Conditional method depending on class attribute

人走茶凉 提交于 2019-12-12 05:28:50

问题


I'm wondering if a conditional method can have his condition on a class attribute.

For instance :

class Class1 
{
   public bool _doStuff;

   [Conditional(_doStuff)]
   public static void Stuff() {
      // Do the stuff
   }
}

Like the [Conditonal("DEBUG")].

Does anyone know about this?


回答1:


This doesn't exist. More to the point, it's illogical.

A method marked as Conditional doesn't take part in the build process if the condition isn't met. This decision can't be made in runtime.

The code is omitted as if it was never written and the executable (or dll) doesn't contain that method.




回答2:


The input of the attribute ought to be a constant. It's used as input for the constructor, at build time.

So in this case it wouldn't work.

If you truly want something conditional, that can be set through variables, I would suggest writing your own attribute class.




回答3:


No there isn't.

1.)You can do is post compile intercepting the generated IL and remove any unwanted generated IL code. Look at - https://msdn.microsoft.com/en-us/library/system.reflection.emit.ilgenerator%28v=vs.110%29.aspx

2.)Use preprocessing tags at class definition and every where you use the class.
For example :

#if test
    internal class SomeClass
    {
      public void SomeMethod(){}
    }
#endif

and :
public static void main()
{
#if test
      var someClass= new SomeClass();
      someClass.SomeMethod();
#endif

}


来源:https://stackoverflow.com/questions/28370427/conditional-method-depending-on-class-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!