[英]InvalidCastException: Specified cast is not valid in Unity
I generate a JSON representation from type Car and then create a System.Object from that json.我从 Car 类型生成一个 JSON 表示,然后从该 json 创建一个 System.Object。 When I try to explicitly convert that object to type Car it shows an error "InvalidCastException: Specified cast is not valid".
当我尝试将 object 显式转换为 Car 类型时,它显示错误“InvalidCastException:指定的转换无效”。 Can anyone explain to me the reason?
谁能给我解释一下原因?
using System;
using UnityEngine;
[Serializable]
class Car
{
public string type;
}
public class Test : MonoBehaviour
{
void Start()
{
Car car = new Car();
car.type = "BMW";
string json = JsonUtility.ToJson(car);
System.Object @object = JsonUtility.FromJson<System.Object>(json);
car = (Car)@object;
Debug.Log(car.type);
}
}
What you are trying to do there is called Down/UpCasting.您在那里尝试执行的操作称为 Down/UpCasting。
In c# object
is the parent class for all other types.在 c# 中,
object
是所有其他类型的父 class。 So you can simply assign an inherited type (like in this case Car
to an object
) variable.所以你可以简单地分配一个继承的类型(比如在这种情况下
Car
给一个object
)变量。 This is called Upcast .这称为Upcast 。
Then when trying to cast from a more generic to a more specific type (in your case object
to Car
this is called Downcast .然后,当尝试从更通用的类型转换为更具体的类型时(在您的情况下
object
到Car
这称为Downcast 。
You only can directly downcast an object
(which btw is simply a type keyword and alias for System.Object
) to Car
if previously this actually was a Car
reference eg您只能直接将
object
(顺便说一句,它只是System.Object
的类型关键字和别名)直接转换为Car
如果以前这实际上是Car
参考,例如
Car car = new Car();
car.type = "BMW";
//string json = JsonUtility.ToJson(car);
//System.Object @object = JsonUtility.FromJson<System.Object>(json);
object @object = car;
car = (Car)@object;
Debug.Log(car.type);
would work since now @object
actually still holds the information for a Car
but boxed into an object
.可以工作,因为现在
@object
实际上仍然保存Car
的信息,但被装箱到object
中。
You can not use你不能使用
System.Object @object = JsonUtility.FromJson<System.Object>(json);
System.Object
is not (de)serializable and makes absolutely no sense as target type here since the type object
also holds no information about the fields you are wanting to deserialize. System.Object
不可(反)序列化,并且在此处作为目标类型绝对没有意义,因为类型object
也不包含有关您要反序列化的字段的信息。 What you want is a Car
not an object
.您想要的是
Car
而不是object
。
So what you could use is所以你可以使用的是
// Here the Car reference returned by FromJson is BOXED into object
System.Object @object = JsonUtility.FromJson<Car>(json);
// Since @object is still a boxed Car value it is now UNBOXED from object to Car
car = (Car)@object;
However, why the whole casting at all ?但是,为什么要进行整个铸造呢? You really rather want to use
你真的很想用
car = JsonUtility.FromJson<Car>(json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.