将对象强制转换为以Type对象表示的类 [英] Cast an object to a class represented as Type object
本文介绍了将对象强制转换为以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);
}
这篇关于将对象强制转换为以Type对象表示的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文