问题
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