简体   繁体   中英

.NET Standard library sets the target preprocessor to NETSTANDARD2_0 when the calling assembly is .NET framework 4.7.2?

I've created three projects: 2 console applications targeting .NET Core 2.1 and .NET Framework 4.7.2 respectively, and a .NET Standard library (targeting both .NET standard 2.0 and .NET core 2.1 by specifying the required TFMs in the TargetFrameworks tag of the .csproj file):

Here is the only class in the .NET Standard library:

public class StdClass
    {
        public string GetCallingPlatform()
        {
#if NETCOREAPP2_1
            return "Core2.1";
#elif NETCOREAPP2_0
            return "Core2.0";

#elif NETSTANDARD2_0
            return "Standard2.0";
#elif NET472
            return "NetFramework4.7.2";
#else
            return "NotSpecified";
#endif
        }

    }

Then, I added a reference to this library from the two console applications and in the Main method of both, I called the GetCallingPlatform :

static void Main(string[] args)
    {
        StdClass stdClass = new StdClass();
        var platform = stdClass.GetCallingPlatform();
        Console.WriteLine(platform);
        Console.ReadLine();
    }

The .NET Core 2.1 console app hits the NETCOREAPP2_1 preprocessor as expected, but the .NET framework console app hits the NETSTANDARD2_0 preprocessor, I was expecting to hit either NET472 or the #else block since the TFM net472 not specified in the TargetFrameworks

Your shared class library will be compiled for all declared target frameworks, each in their own directory under bin\\Debug , so bin\\Debug\\netcoreapp2.1 and bin\\Debug\\netstandard2.0 .

When compiling those versions targeting those frameworks, the compiler directive will be applied. The .NET Standard version will return "Standard2.0" and the .NET Core verison will return "Core2.1".

After this library has been compiled, your console applications will be compiled. Your .NET Core application will reference the .NET Core version of the library (and hence print "Core2.1"), and the .NET Framework 4.7.2 version, which can reference .NET Standard libraries, will print "Standard2.0" - because that's been baked into that version of the library.

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