2016-07-28 26 views
4

幾個框架我有一個圖書館,在我的代碼的一些點定標.NET Corenet45我需要使用反射像這樣:編譯器指令如何對使用.NET的核心

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目標上同幾個框架項目/庫?

+0

@JonSkeet帖子創建於一年前,所以這樣的嘗試是可以接受的。我同意今天沒有人再這樣做了。 –

+0

@LexLi:好點 - 我只看到它,因爲它是在3小時前編輯的。將刪除我的評論... –

回答

0

雖然在.net core做一些研究,我橫跨this question和接受的答案有東西在吸引我眼球的project.json文件代碼來了,這裏是一個片段:

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

,你可以在裏面的看buildOptions有一個define: [ NET46 ]這是您可以沿着#if#elif指令使用的標籤。所以即使我不知道(或者沒有)一種方法來引用這些版本的框架,我也可以使用我自己的。

+0

任何使用最新.NET Core SDK工具的人都應該遵循此官方文章https://docs.microsoft.com/en-us/dotnet/standard/frameworks使用內置定義的符號定義你自己的。 –