简体   繁体   English

在对象派生类中强制转换对象基类

[英]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 . 您不能从CfgObjectCfgService ,而只能从CfgServiceCfgObject 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.

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