Compiler directives for targeting multiple frameworks using .NET Core

I have library targeting .NET Coreand net45at some point in my code I need to use reflection as follows:

var type = obj.GetType();
var properties = type.GetProperties().ToList();

if (type.IsPrimitive || type.IsEnum || properties.Count == 0)
    return new Dictionary<string, object> { { unnamed, obj } };

Now I am moving my library to also support .NET Core, so I created a new project .net core library, this is mineproject.json

{
  "version": "1.0.0",
  "dependencies": {
    "Wen.Logging.Abstractions": "1.0.0"
  },
  "frameworks": {
    "net45": {
      "frameworkAssemblies": {
        "System.Reflection": "4.0.0.0"
      },
      "dependencies": {
        "Newtonsoft.Json": "6.0.4",
        "NLog": "4.3.5"
      }
    },
    "netstandard1.6": {
      "imports": "dnxcore50",
      "dependencies": {
        "NETStandard.Library": "1.6.0",
        "System.Reflection.TypeExtensions": "4.1.0",
        "Newtonsoft.Json": "8.0.2",
        "NLog": "4.4.0-*"
      }
    }
  }
}

My classes are added, and the compiler complains about the properties, type.IsPrimitiveand types.IsEnumso I decided to use compiler directives to do something like this:

var type = obj.GetType();
var properties = type.GetProperties().ToList();

#if net45    

if (type.IsPrimitive || type.IsEnum || properties.Count == 0)
    return new Dictionary<string, object> { { unnamed, obj } };

#elif netstandard16

//... some code

#endif

, net45 ( , VS .NET Core), , , #elif #endif, , #else, :

var typeInfo = type.GetTypeInfo();
if(typeInfo.IsPrimitive || typeInfo.IsEnum || properties.Count == 0)
    return new Dictionary<string, object> { { unnamed, obj } };

:

#if /?

+4
1

.net core, , - project.json, , :

"frameworks": {
"net46": {
  "buildOptions": {
    "define": [ "NET46" ]
  }
},

buildOptions, define: [ NET46 ], , #if #elif. , ( ) , .

0

Source: https://habr.com/ru/post/1649436/


All Articles