簡體   English   中英

在對象派生類中強制轉換對象基類

[英]Cast Object Base Class in Object Derived Class

我正在運行以下代碼:

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();
...

我總是收到

System.InvalidCastException(無法將類型為“ CfgObject”的對象轉換為類型為“ CfgService”的對象)

正確的做法是什么?

您不能從CfgObjectCfgService ,而只能從CfgServiceCfgObject 鑄造總是從派生類到基類進行。

如果您確實想要CfgService的實例, CfgService需要創建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