我有几个课程
public class JsonWorldRanking
{
public int no { get; set; }
public string deviceid { get; set; }
public string name { get; set; }
public int clicks { get; set; }
public int country { get; set; }
}
public class JsonNationalRanking
{
public int no { get; set; }
public string deviceid { get; set; }
public string name { get; set; }
public int clicks { get; set; }
}
public class JsonCountryRanking
{
public int no { get; set; }
public int countryIndexRanking { get; set; }
public int clicks { get; set; }
}
我希望根据特定条件为Json反序列化操作选择这三个类中的任何一个。因此,如果使用switch case,我如何使下面的WHICHLASS表示正确的类?像
这样的东西switch value
{
case 0:
WHICHCLASS = JsonWorldRanking;
break;
case 1:
WHICHCLASS = JsonNationalRanking;
break;
case 2:
WHICHCLASS = JsonCountryRanking
break;
}
...
var deserialized = JsonConvert.DeserializeObject<List<WHICHCLASS>>(r.EventArgs.Result);
答案 0 :(得分:0)
我认为创建T的通用方法更好。但这也可以用
Type destinationType = null;
switch value
{
case 0:
destinationType = typeof(JsonWorldRanking);
break;
case 1:
destinationType = typeof(JsonNationalRanking);
break;
case 2:
destinationType = typeof(JsonCountryRanking);
break;
}
...
Type listType = typeof(List<>);
Type[] typeArgs = {destinationType};
type requiredGenericListType = listType.MakeGenericType(typeArgs);
var deserialized = JsonConvert.Deserialize(r.EventArgs.Result, requiredGenericListType );