gpt4 book ai didi

c# - 用于使用 .NET Core 的多个框架的编译器指令

转载 作者:行者123 更新时间:2023-11-30 12:56:46 28 4
gpt4 key购买 nike

我的代码中有一个针对 .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 进行一些研究时,我遇到了 this question在接受的答案中,project.json 文件代码中的某些内容引起了我的注意,这是一个片段:

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

正如您在 buildOptions 中看到的那样,有一个 define: [ NET46 ] 这是您可以在 #if 中使用的标签和 #elif 指令。因此,即使我不知道(或没有)一种方法来引用框架的这些版本,我也可以使用自己的方法。

关于c# - 用于使用 .NET Core 的多个框架的编译器指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38641197/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com