将对象强制转换为表示为Type对象的类

本文关键字:对象 Type 表示 转换 | 更新日期: 2023-09-27 18:11:09

好吧,我甚至不知道标题是否有任何意义,但我很难描述我需要做什么。请看一下这个例子。

我正在做这个:

(SportsParent)JsonConvert.DeserializeObject<SportsParent>(jsonObj);

但是,如果我想有类名"sportparent"存储在一个字符串中,并从它创建一个类型对象。然后使用Type对象进行类型转换。

像这样:

Type type = Type.GetType("myNanespace.SportsParent");
(type )JsonConvert.DeserializeObject<type >(jsonObj);

谢谢。

将对象强制转换为表示为Type对象的类

接受TypeJsonConvert.DeserializeObject过载。试试这个:

string typeName = "myNamespace.SportsParent";
Type type = Type.GetType(typeName);
object obj = JsonConvert.DeserializeObject(jsonObj, type);

然后,在后面的代码中…

if (obj is SportsParent)
{
    SportsParent sp = (SportsParent) obj;
    // do something with sp here
}
else if (obj is SomeOtherType)
{
    SomeOtherType sot = (SomeOtherType) obj;
    // handle other type
}
else
{
    throw new Exception("Unexpected type: " + obj.GetType().FullName);
}