0

我有几节课

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);
4

1 回答 1

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 );
于 2013-01-09T13:16:01.580 回答