我希望在Visual Studio 2010中使用一些.NET 4.0的功能,但仍然针对.NET 3.5进行目标设置。基本上我想要像这样的东西:
if (.NET 4 installed) then
execute .NET 4 feature
这是一个可选功能,如果系统安装了.NET 4.0,我希望它能够运行。如果系统只有.NET 3.5,则该功能不会执行,因为它对应用程序并不是必要的。
我希望在Visual Studio 2010中使用一些.NET 4.0的功能,但仍然针对.NET 3.5进行目标设置。基本上我想要像这样的东西:
if (.NET 4 installed) then
execute .NET 4 feature
这是一个可选功能,如果系统安装了.NET 4.0,我希望它能够运行。如果系统只有.NET 3.5,则该功能不会执行,因为它对应用程序并不是必要的。
首先,您需要针对3.5版本的框架进行目标定位,但通过使用类似于以下的App.config
配置文件,使您的程序能够由4.0框架加载(来自如何强制应用程序使用.NET 3.5或更高版本?):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0"/>
<supportedRuntime version="v2.0.50727"/>
</startup>
</configuration>
关于如何激活4.0功能,取决于您想使用的功能。如果是内置类中的方法,只需查找并使用该方法(如果存在)。以下是C#示例(同样适用于VB):
var textOptions = Type.GetType("System.Windows.Media.TextOptions, " +
"PresentationFramework, Version=4.0.0.0, " +
"Culture=neutral, PublicKeyToken=31bf3856ad364e35");
if (textOptions != null)
{
var setMode = textOptions.GetMethod("SetTextFormattingMode");
if (setMode != null)
// don't bother to lookup TextFormattingMode.Display -- we know it's 1
setMode.Invoke(null, new object[] { this, 1 });
}
MainWindow
构造函数中,它将在运行于.NET 4.0框架下的应用程序中设置TextFormattingMode
为Display
,而在3.5下则不会有任何效果。using System.Numerics;
namespace Factorial
{
public class BigFactorial
{
public static object Factorial(int arg)
{
BigInteger accum = 1; // BigInteger is in 4.0 only
while (arg > 0)
accum *= arg--;
return accum;
}
}
}
using System;
using System.Reflection;
namespace runtime
{
class Program
{
static MethodInfo factorial;
static Program()
{ // look for Factorial.dll
try
{
factorial = Assembly.LoadFrom("Factorial.dll")
.GetType("Factorial.BigFactorial")
.GetMethod("Factorial");
}
catch
{ // ignore errors; we just won't get this feature
}
}
static object Factorial(int arg)
{
// if the feature is needed and available, use it
if (arg > 20 && factorial != null)
return factorial.Invoke(null, new object[] { arg });
// default to regular behavior
long accum = 1;
while (arg > 0)
accum = checked(accum * arg--);
return accum;
}
static void Main(string[] args)
{
try
{
for (int i = 0; i < 25; i++)
Console.WriteLine(i + ": " + Factorial(i));
}
catch (OverflowException)
{
if (Environment.Version.Major == 4)
Console.WriteLine("Factorial function couldn't be found");
else
Console.WriteLine("You're running " + Environment.Version);
}
}
}
}
如果您将EXE和Factorial.DLL复制到同一个目录中并运行它,您将获得所有小于4.0的前25个阶乘,但只有在3.5版本下才能获取前20个阶乘,并且会显示错误消息(或者如果找不到DLL)。
不可以。一个有限的选项是使用条件编译,像这样:
#if NET40
some 4.0 code
#else
some 3.5 code
#endif
主要问题是,你不能在.NET 4 CLR或其相反版本上运行为.NET 3.5编译的代码。你需要重新为.NET 4编译。
所以你将有两个可执行文件,一个是.NET 3.5的,另一个是.NET 4的。两者都有相同的代码,但你可以使用预处理器指令,具体来说是#IF指令,在这两者之间进行区别。
然后在两个项目的配置中指定特定的指令。