Luk*_*uke 5 .net vb.net .net-4.0 visual-studio-2010 .net-3.5
我想使用.NET 4.0中的一些功能,但仍然在Visual Studio 2010中定位.NET 3.5.基本上我想要有类似的东西:
if (.NET 4 installed) then
execute .NET 4 feature
Run Code Online (Sandbox Code Playgroud)
这是一个可选功能,如果系统安装了.NET 4.0,我只想运行它.如果系统只有.NET 3.5,那么该功能将不会执行,因为它不是对应用程序至关重要的东西.
首先,您必须以3.5版本的框架为目标,但是通过具有App.config如下所示的(从如何强制应用程序使用.NET 3.5或更高版本?)使4.0程序可以加载程序:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0"/>
<supportedRuntime version="v2.0.50727"/>
</startup>
</configuration>
Run Code Online (Sandbox Code Playgroud)
至于如何激活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 });
}
Run Code Online (Sandbox Code Playgroud)
如果将它放在MainWindow构造函数中,它将设置TextFormattingMode为Display在.NET 4.0框架下运行的应用程序,并且在3.5下不执行任何操作.
如果要使用3.5中不可用的类型,则必须为其创建新的程序集.例如,创建一个名为"Factorial"的类库项目,其代码如下(您必须添加对System.Numerics的引用;相同的C#免责声明):
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后用这样的代码创建一个目标为3.5的项目(相同的C#免责声明):
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您将EXE和Factorial.DLL复制到同一目录并运行它,您将获得4.0以下的所有前25个阶乘,只有最多20个阶乘以及3.5上的错误消息(或者如果它找不到DLL).
| 归档时间: |
|
| 查看次数: |
1588 次 |
| 最近记录: |