jeudi 28 juillet 2016

reflection while targeting several framworks

I have a library targeting .net core and net45 at some point on my code I need to use reflection like this:

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 porting my library to also support .net core so I made a new .net core library project, this is my project.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-*"
      }
    }
  }
}

added my classes and the compiler complains about the type.IsPrimitive and types.IsEnum properties so I thought 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

Once I do this the code inside the net45 is grayed out (I think because VS is seeing it as .net core) but then no matter what tag I set between the #elif and #endif is also grayed. I have also tried with #else and then I can do:

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

however my question remains:

What tags should I use on my code on the compiler directives #if to target several frameworks on the same project/library?





Aucun commentaire:

Enregistrer un commentaire