class childType: MainType{}
MainType mObj = GetData();
childType cObj = (childType)mObj;
我怎麼能投上述鑄造一種類型到另
childType cObj = (childType)mObj;
我得到這個錯誤:
Unable to cast object of type 'System.Data.Entity.DynamicProxies.MainType_F04DC499C53D433B05ABEDEE7191583DB11728F68B18671613EF0E5AC158DD0D' to type 'ChildType'.
'GetData();'返回什麼類型?它真的是'childType'嗎? – 2013-04-30 22:11:34
如果您的'GetData()'方法返回'MainType'的一個實例,那麼您無法合法地將其轉換爲'childType'。如果'GetData()'返回一個'childType'對象或者派生自它的東西,那麼這個強制轉換就可以工作。這是設計。你可以嘗試'childType cObj = mObj作爲childType;'如果類型不兼容,將導致null。 – Corey 2013-04-30 22:11:42
@DStanley GetData()返回MainType – HaBo 2013-04-30 22:50:49