简体   繁体   中英

In Visual Studio, is it possible to target a .NET 4.x CLR but a 2.0 class library API?

When you select the target framework of a C# project in Visual Studio, you actually select three different things at once (as far as I understand).

Selecting .NET 4.7.2 will select:

  • the language version (eg C# 7.2)
  • the CRL (common language runtime) version (eg 4.5)
  • and the BCL (base class library) version (eg 4.7.2)

Now, is it possible to somehow configure these things independently? I understand there are dependencies, but targeting a lower BCL API should work, right?

The reason is this: my project is a C# class library that is used inside a Unity3D application. Unity has a 4.x (compatible) CLR, but let's you chose between a .NET Standard 2.0 API and a 4.x. It generally makes sense to target 2.0 because it is smaller and 4.x does not work on all platforms that Unity supports.

It would be great if I could replicate this configuration in Visual Studio. Otherwise I might accidentally make an invalid (ie > 2.0) API call in my dll code and will only find out when the code crashes with a 'class/function not found' in Unity.

The language version can be set completely independently via <LangVersion> in the csproj, ie

<LangVersion>8.0</LangVersion>

The CLR and BCL versions are... complex. You're really targeting a TFM here. It sounds like you want (again, in the csproj)

<TargetFramework>netstandard2.0</TargetFramework>

The actual CLR (runtime) is determined by whatever runs it , not the library. But you can multi-target, if that becomes useful, ie

<TargetFrameworks>netstandard2.0;net472</TargetFrameworks>

and configure different dependencies and #if etc for different platforms, to make the most of each. Whether unity can properly consume a multi-targeted package is another question, that I can't answer.

You can edit the csproj at any point; you aren't tied to what is generated from the template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM