[英]Cast an object to a class represented as Type object
好的,我什至不知道標題是否有意義,但是我很難描述我需要做什么。 因此,請看示例plz。
我正在這樣做:
(SportsParent)JsonConvert.DeserializeObject<SportsParent>(jsonObj);
但是,如果我想將類名稱“ SportsParent”存儲在字符串中,並從中創建Type對象,該怎么辦? 然后使用該Type對象進行投射。
像這樣:
Type type = Type.GetType("myNanespace.SportsParent");
(type )JsonConvert.DeserializeObject<type >(jsonObj);
謝謝。
JsonConvert.DeserializeObject
有一個接受Type
的重載。 嘗試這個:
string typeName = "myNamespace.SportsParent";
Type type = Type.GetType(typeName);
object obj = JsonConvert.DeserializeObject(jsonObj, type);
然后,稍后在您的代碼中...
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.