c# – 使用.NET Core定位多个框架的编译器指令
发布时间:2020-12-15 21:01:07 所属栏目:百科 来源:网络整理
导读:我的代码中有一个针对.NET Core和net45的库,我需要使用这样的反射: var type = obj.GetType();var properties = type.GetProperties().ToList();if (type.IsPrimitive || type.IsEnum || properties.Count == 0) return new Dictionarystring,object { { un
我的代码中有一个针对.NET Core和net45的库,我需要使用这样的反射:
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核心所以我创建了一个新的.net核心库项目,这是我的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.IsPrimitive和types.IsEnum属性,所以我想用编译器指令做这样的事情: var type = obj.GetType(); var properties = type.GetProperties().ToList(); #if net45 if (type.IsPrimitive || type.IsEnum || properties.Count == 0) return new Dictionary<string,obj } }; #elif netstandard16 //... some code #endif 一旦我这样做,net45内的代码就会变灰(我认为因为VS将其视为.net核心)但是无论我在#elif和#endif之间设置了什么标记,它也会变灰.我也试过#else然后我可以做: var typeInfo = type.GetTypeInfo(); if(typeInfo.IsPrimitive || typeInfo.IsEnum || properties.Count == 0) return new Dictionary<string,obj } }; 不过我的问题仍然是: 我应该在编译器指令的代码上使用什么标签#if来定位同一个项目/库中的几个框架? 解决方法
在对.net核心进行一些研究时,我遇到了
this question,并且在接受的答案中,project.json文件代码中引起了我的注意,这里有一个片段:
"frameworks": { "net46": { "buildOptions": { "define": [ "NET46" ] } }, 正如您在buildOptions中看到的那样,有一个define:[NET46],它是您可以在#if和#elif指令中使用的标记.所以即使我不知道(或者没有)引用框架的那些版本的方法,我也可以使用自己的版本. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |