简体   繁体   English

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

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

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. 因此,请看示例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. 但是,如果我想将类名称“ SportsParent”存储在字符串中,并从中创建Type对象,该怎么办? And then use that Type object for casting. 然后使用该Type对象进行投射。

Something like that: 像这样:

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

Thank you. 谢谢。

There is an overload of JsonConvert.DeserializeObject that accepts a Type . JsonConvert.DeserializeObject有一个接受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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM