简体   繁体   中英

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')

What is the correct way of doing?

You cannot cast from CfgObject to CfgService , only from CfgService to 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 . 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 .

CfgObject obj1 = new CfgService((object)1);
CfgService service = (CfgService)obj1;
service.GetObject();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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