针对使用.NET Core的多个框架的编译器指令

本文关键字:编译器 指令 框架 Core NET | 更新日期: 2023-09-27 17:59:03

我有一个针对.NET Corenet45的库,在我的代码上的某个时刻,我需要使用这样的反射:

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

现在我正在移植我的库来支持.net core,所以我做了一个新的.net core library项目,这是我的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-*"
      }
    }
  }
}

添加了我的类,编译器抱怨type.IsPrimitivetypes.IsEnum属性,所以我想使用编译器指令来做这样的事情:

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上的代码中使用哪些标记来针对同一项目/库上的多个框架?

针对使用.NET Core的多个框架的编译器指令

在对.net core进行一些研究时,我遇到了这个问题,在公认的答案中,project.json文件代码中有一些东西引起了我的注意,下面是一个片段:

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

正如您所看到的,在buildOptions内部有一个define: [ NET46 ],它是可以与#if#elif指令一起使用的标记。所以,即使我不知道(或者没有)引用这些版本的框架的方法,我也可以使用我自己的。