[英]Cast Object Base Class in Object Derived Class
I'm running the following code: 我正在运行以下代码:
public class CfgObject
{
protected object _inst;
public CfgObject(object inst) { _inst = inst; }
}
public class CfgService : CfgObject
{
public object GetObject() { return _inst; }
public CfgService(object inst) : base(inst) {}
}
...
CfgObject obj1 = new CfgObject((object)1);
CfgService service = (CfgService)obj1;
service.GetObject();
...
I always receive 我总是收到
System.InvalidCastException (Unable to cast object of type 'CfgObject' to type 'CfgService')
System.InvalidCastException(无法将类型为“ CfgObject”的对象转换为类型为“ CfgService”的对象)
What is the correct way of doing? 正确的做法是什么?
You cannot cast from CfgObject
to CfgService
, only from CfgService
to CfgObject
. 您不能从
CfgObject
为CfgService
,而只能从CfgService
为CfgObject
。 Casting is always done from derived to base class. 铸造总是从派生类到基类进行。
If you really want an instance of CfgService
you need to create an instance of CfgService
. 如果您确实想要
CfgService
的实例, CfgService
需要创建CfgService
的实例。 If you create a supertype (base) you cannot cast it to a subtype. 如果创建超类型(基本),则无法将其强制转换为子类型。 You could do the following, although it would be rather pointless because you might as well just declare
obj1
as a CfgService
. 您可以执行以下操作,尽管这毫无意义,因为您最好将
obj1
声明为CfgService
。
CfgObject obj1 = new CfgService((object)1);
CfgService service = (CfgService)obj1;
service.GetObject();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.