What's the best way to target multiple versions of the .NET framework?

后端 未结 3 957
谎友^
谎友^ 2021-01-30 16:24

I\'m building a class library and I will deploy it a NuGet package, which lets me choose different assemblies to be added as references based on the .NET framework version of th

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 17:10

    A simple approach is to add another .csproj file in the same folder, and configure it to build a different framework version. This avoids having to add links to files, as both projects are essentially views over the same folder structure.

    Say you have the structure:

    - MyLibrary\
      - MyLibrary.sln
      - MyLibrary\
        - MyLibrary.csproj
        - Program.cs
    

    Duplicate MyLibrary.csproj to the same folder and edit to change a few things:

    • just make a new GUID for this element's value
    • specify the alternative version here, eg: v4.5 or v3.5
    • (for Debug and Release) set this to a unique path, such as bin\Debug\net45 and bin\Debug\net45, to allow each project's output to end up in a unique location

    You must also add a new element to the non-conditional element, so that the two projects don't collide in the obj folder during parallel builds. This is important, and protects against weird race condition bugs.

    
      obj\net45\
    

    Finally, add this new project to your existing solution.

    This approach works hand in hand with defining compilation switches such as NET35 and NET45, and using #if NET35 / #endif directives.

    Two open source projects that use this technique are MetadataExtractor and NetMQ. You can refer to them in case you hit trouble.

提交回复
热议问题