4

我正在尝试编写一系列在组织内的多个应用程序之间使用的类库。其中一些应用程序以 .NET 3.5 为目标,一些以 4.0 为目标。

我们希望提供两个版本的程序集,一个面向 3.5,一个面向 4.0,以便主机应用程序可以选择最适合它们的程序集。

3.5 和 4.0 版本之间存在一些细微差别:

  • 由于被 .NET 4.0 版本取代,一些类已被删除。
  • 添加了一些类以帮助使用 .NET 4.0 引入的类。
  • 一些类在 4.0 版本中进行了修改,以利用 4.0 中一些增强的线程支持。

是否有任何解决方案可以让我重新使用代码库的重叠部分并防止简单地分叉源树?

我的目标是生成针对其指定框架的程序集的多个版本,这些程序集可以滚动到 NuGet 包中并在我们的内部提要中公开。

4

3 回答 3

6

这听起来像是条件编译器指令的工作。

胡椒你的代码:

#If NET35
...
#End If

#If NET40
...
#End If

从这里开始,您必须将NET35NET40编译常量添加到您的项目中,我建议您首先在配置管理器中创建自定义配置,例如DebugNET35DebugNET40ReleaseNET35ReleaseNET40。创建这些配置后,您可以切换到每个配置并转到项目的高级编译选项,您可以在其中设置自定义常量NET35NET40,具体取决于当前配置。

您也可以在此对话框中设置目标框架,但它将全局设置您的框架版本。要为每个配置设置自定义目标框架,请遵循Pierre 的步骤

之后,选择一个配置并编译!我已经使用这种技术为应用程序的“演示”和“完整”版本共享相同的代码库。

希望未来版本的 Visual Studio 将包含自动定义的框架版本:https ://connect.microsoft.com/VisualStudio/feedback/details/113323/include-framework-version-defines-automatically

编辑: .NET Framework 博客中有一篇新文章讨论了在 Visual Studio 2010 和 2012 中编写可移植代码库:http: //blogs.msdn.com/b/dotnet/archive/2012/07/06/targeting-multiple -platforms-with-portable-code-overview.aspx,这看起来像一个更清洁的解决方案。

于 2012-06-15T14:58:45.740 回答
3

可能有更好的方法来做到这一点,但我在针对不同平台时做了以下操作。(使用 XNA 的 Xbox 与 PC)

您在配置中创建多个具有不同平台目标的 *.csproj。例如,如果它是一个项目,您将有 2 个 *.csproj 文件,一个用于 .NET 3.5,另一个用于 .NET 4.0。

在配置管理器中,您将为每个版本设置不同的平台。*.csproj(s) 实际上会引用相同的文件。您还可以设置构建条件符号,以便可以针对 .NET 3.5 和 .NET 4.0 定位代码片段。此外,如果您需要重写整个文件,*.csproj(s) 将引用他们自己的文件。

于 2012-06-15T14:55:36.193 回答
1

If you're planning on writing a family of class libraries that will support multiple .NET frameworks (and/or platforms), you may want to create a "Portable Class Library".

Full details are in the blog post Targeting Multiple Platforms with Portable Code (Overview). In Visual Studio 2012, you simply create a new "Portable Class Library" project, whereas in Visual Studio 2010 you'll need to install the Portable Library Tools first.

With a PCL project, you can target the following platforms:

  • .NET Framework 4, 4.0.3, and 4.5
  • .NET for Metro style apps (which I presume includes Windows Phone 8 and Windows 8 RT)
  • Windows Phone 7.x
  • Silverlight 4 and 5
  • Xbox 360

However, note that .NET Framework 3.5 is not currently included in this list. The Portable Library Tools were written so that other platforms can be added in the future, with Mono support currently at the top of the list.

于 2012-07-10T14:49:04.147 回答