将对象强制转换为以Type对象表示的类
问题描述:
好吧,我什至不知道标题是否有意义,但是我很难描述我需要做什么。因此,请看示例plz。
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.
我正在这样做:
(SportsParent)JsonConvert.DeserializeObject<SportsParent>(jsonObj);
但是如果我想将类名 SportsParent存储在字符串中并创建一个从中键入对象。然后使用该Type对象进行投射。
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.
类似这样的东西:
Type type = Type.GetType("myNanespace.SportsParent");
(type )JsonConvert.DeserializeObject<type >(jsonObj);
谢谢。
答
JsonConvert.DeserializeObject
的重载可以接受 Type
。试试这个:
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);
}