Cast an object to a class represented as Type object [duplicate]

廉价感情. 提交于 2020-07-10 11:33:06

问题


Ok i dont even know if the title makes any sense, but i am having difficulty describing what i need to do. So take a look at the example plz.

I am doing this:

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

But what if i wanted to have the class name "SportsParent" stored in a string, and create a Type object from it. And then use that Type object for casting.

Something like that:

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

Thank you.


回答1:


There is an overload of JsonConvert.DeserializeObject that accepts a Type. Try this:

string typeName = "myNamespace.SportsParent";

Type type = Type.GetType(typeName);
object obj = JsonConvert.DeserializeObject(jsonObj, type);

Then, later in your code...

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


来源:https://stackoverflow.com/questions/24508081/cast-an-object-to-a-class-represented-as-type-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!