在编译时检测目标框架版本 [英] Detect target framework version at compile time
问题描述
我有一些code,这使得使用扩展方法,但使用VS2008下编译.NET 2.0编译。为了推动这项工作,我不得不宣布ExtensionAttribute:
I have some code which makes use of Extension Methods, but compiles under .NET 2.0 using the compiler in VS2008. To facilitate this, I had to declare ExtensionAttribute:
/// <summary>
/// ExtensionAttribute is required to define extension methods under .NET 2.0
/// </summary>
public sealed class ExtensionAttribute : Attribute
{
}
不过,我现在倒是像在该类包含也可以在.NET 3.0,3.5和4.0编译库 - 无警告ExtensionAttribute在多个地方定义的
However, I'd now like the library in which that class is contained to also be compilable under .NET 3.0, 3.5 and 4.0 - without the 'ExtensionAttribute is defined in multiple places' warning.
有没有我可以用它来只包括ExtensionAttribute当对象而定的框架版本.NET 2的编译时间指令?
Is there any compile time directive I can use to only include the ExtensionAttribute when the framework version being targetted is .NET 2?
推荐答案
链接所以用创建N个不同的配置'的问题当然是一个选择,但是当我有必要为了这个,我刚添加条件DefineConstants元素,所以在我调试|调试现有DefineConstants后的x86(例如); TRACE,我加了这2,检查是在的csproj文件的第一的PropertyGroup设置TFV值
The linked SO question with 'create N different configurations' is certainly one option, but when I had a need for this I just added conditional DefineConstants elements, so in my Debug|x86 (for instance) after the existing DefineConstants for DEBUG;TRACE, I added these 2, checking the value in TFV that was set in the first PropertyGroup of the csproj file.
<DefineConstants Condition=" '$(TargetFrameworkVersion)' == 'v4.0' ">RUNNING_ON_4</DefineConstants>
<DefineConstants Condition=" '$(TargetFrameworkVersion)' != 'v4.0' ">NOT_RUNNING_ON_4</DefineConstants>
您不需要两个,很明显,但它只是没有给这两个EQ和NE行为的例子 - 的#else和#elif做工精细太:)
You don't need both, obviously, but it's just there to give examples of both eq and ne behavior - #else and #elif work fine too :)
class Program
{
static void Main(string[] args)
{
#if RUNNING_ON_4
Console.WriteLine("RUNNING_ON_4 was set");
#endif
#if NOT_RUNNING_ON_4
Console.WriteLine("NOT_RUNNING_ON_4 was set");
#endif
}
}
然后我可以瞄准3.5和4.0,它会做正确的事之间切换。
I could then switch between targeting 3.5 and 4.0 and it would do the right thing.
这篇关于在编译时检测目标框架版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!