开发者

How do I use a preprocessor condition with assembly version?

Currently in my code I have this if-statement:

if (System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Major > 0)
{
     //Stuff that will execute when we get out of beta
}

Since it is possible to predict the outcome of this statement at compile time I wonder, just out of curiosity, if there is a way to replace it with something like

#if开发者_高级运维 MAJOR_VERION > 0
//Do stuff
#endif

Additionally, if this is possible, is it good or bad .net practice?


You can't do that as such - preprocessor symbols are either "on" or "off" (defined or not), rather than having numeric values.

You could easily define a BETA preprocessor symbol though, in appropriate project configurations. Then you can just remove it when you're out of beta.

(I'm not sure it's generally a good idea to have conditionalized code like that, mind you. If you're not going to execute that code until you're out of beta, how will you beta test that code?)


You can only use == and != conditional in preprocessor directives in C#.

See MSDN:

You can use the operators == (equality), != (inequality) only to test for true or false . True means the symbol is defined. The statement #if DEBUG has the same meaning as #if (DEBUG == true).

You can define symbols yourself in, the project file, the command line or in code (#define).


Since it is possible to predict the outcome of this statement at compile time

It is not. The reference assembly doesn't have to match the runtime assembly. A publisher policy or a <BindingRedirect> element in the .config file allows another version of the assembly to get loaded at runtime without getting an exception. Assembly binding in .NET is quite dynamic. You can use an #if directive in your code (don't use expressions), not untypical when you have to support multiple platform targets, but your original approach is the more universal solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜