[英]Passing a (local) variable to a generic method as Type
我想做的事情,非常簡短的版本摘要:
var localType = typeof(MyDTOClass);
var result = MyGenericMethod<localType>(string path);
VisualStudio告訴我dtoType是可變的,但像類型一樣使用。
長版:我有以下字典,該字典用於從磁盤讀取某些文件,然后使用(反)序列化器將其轉換為對象。 json文件的內容幾乎相同,因此我僅舉一個例子:Json目錄,對象數組:
[{
"id": "1",
"areaType": "2",
"backgroundImagePath": "path",}, {
"id": "2",
"areaType": "2",
"backgroundImagePath": "path",}, {
"id": "99",
"areaType": "1",
"backgroundImagePath": "path",}]
詞典內容:
var filesToParse = new Dictionary<string, Type>{
{ "area.json",typeof(AreaDto) },
{ "areaObject.json",typeof(AreaObjectDto) },
{ "monsterSymbol.json",typeof(MonsterSymbolDto) },
};
檢索json內容內容的代碼:
IEnumerable GetDeserializedJson(string pathToJsonFile, Type dtoType) {
IEnumerable result;
using (TextReader file = File.OpenText(pathToJsonFile)) {
result = JsonSerializer.DeserializeFromReader<IEnumerable<dtoType>>(file);
}
return result.OfType<dtoType>.Where(x => x != null);
}
我的問題是以下幾行
result = JsonSerializer.DeserializeFromReader<dtoType>(file);
result.OfType<dtoType>.Where(x => x != null);
dtoType是變量,但像類型一樣使用。 我知道這是一個變量,但它是Type的變量。 您能否解釋一下為什么我不能傳遞此類型變量,如果可能的話,如何進一步解決我的問題? 以下是我(想)如何調用我的GetDeserializedJson的方法
foreach(var keyValuePair in filesToParse){
GetDeserializedJson<keyValuePair.Value>(keyValuePair.Key);
}
提前致謝
只需使用非通用的DeserializeFromReader(reader, Type)
方法,它將返回一個object
。 像這樣:
result = JsonSerializer.DeserializeFromReader(file, typeof(dtotype));
或者,如果dtoType
是Type
實例,則只需
result = JsonSerializer.DeserializeFromReader(file, dtotype);
您必須決定是否要使用泛型或類型,但是不能即時“切換”到泛型。 說到這個例子
var localType = typeof(MyDTOClass);
var result = MyGenericMethod<localType>(string path);
您只是不需要第一行,而是
var result = MyGenericMethod<MyDTOClass>(string path);
談到其他樣品
IEnumerable GetDeserializedJson(string pathToJsonFile, Type dtoType)
{
IEnumerable result;
using (TextReader file = File.OpenText(pathToJsonFile))
{
result = JsonSerializer.DeserializeFromReader<IEnumerable<dtoType>>(file);
}
return result.OfType<dtoType>.Where(x => x != null);
}
您可以改為聲明通用方法:
IEnumerable<TDto> GetDeserializedJson<TDto>(string pathToJsonFile) where TDto : DtoBaseClass
{
IEnumerable<TDto> result;
using (TextReader file = File.OpenText(pathToJsonFile))
{
result = JsonSerializer.DeserializeFromReader<IEnumerable<TDto>>(file);
}
return result.OfType<TDto>.Where(x => x != null);
}
這樣,您甚至不必where TDto : DtoBaseClass
為類型,並且where TDto : DtoBaseClass
具有約束where TDto : DtoBaseClass
因此編譯器將不允許您使用類,這些類不是從您的基本dto類派生的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.