2015-11-07 33 views
0

在stackoverflow中有類似線程的一些重複,但這不完全相同,所以我在這裏再次發佈。我們來考慮下面的例子。無法爲接口隱式轉換類型

public interface ILeft 
    { 
     void Move(); 
    } 

    public class MoveableOject : ILeft 
    { 
     //without public we get an error 
     public void Move() 
     { 
      Console.WriteLine("Left moving"); 
     } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      MoveableOject mo = new MoveableOject(); 
      mo.Move(); 
      Console.ReadKey(); 
     } 
    } 

一切都很好。現在讓我們考慮一下ILeft的顯式實現。爲什麼評論欄提供了上述錯誤信息?

class MoveableOject : ILeft 
{ 
    void ILeft.Move() 
    { 
     Console.WriteLine("Left moving"); 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     MoveableOject mo = new MoveableOject(); 
     // MoveableOject moWithErrorObject = (ILeft) new MoveableOject(); <-- 
     ((ILeft)mo).Move(); 
     ((ILeft)new MoveableOject()).Move(); 

     Console.ReadKey(); 
    } 
} 

編輯:11月8日/ 2015年MoveableOject錯誤的說法應該是ILeft理解,誤我把它放在那裏。爲什麼我發佈了我無法解釋它的原因,讓我們使用該對象並按照以下方式傳遞給一個方法。

public static void ExpectDerivedPassedDerived(MoveableOject passedObject) 
{ 
    passedObject.Move(); 
} 

現在,如果我從Main調用方法應該工作嗎?但它並不是因爲我有明確的實現,但如果我使用公共關鍵字實現,那麼這將很好,我正在尋找一個解釋。

ExpectDerivedPassedDerived(mo); //mo is MoveableOject type 
+1

這與顯式接口無關。 'MoveableObject'繼承自'ILeft',而不是相反。 – Rhumborl

+0

顯式實現允許您的方法僅在作爲接口本身進行投射時纔可訪問。在這種情況下。 – CodeNotFound

+0

任何人都可以對編輯後的代碼發表評論嗎?這是我的初衷,想問這個問題。謝謝。 – RotatingWheel

回答

2

您創建一個新的MoveableOject,強制轉換爲ILeft,然後嘗試assing的ILeft你從鑄造到MoveableObject參考了。 Compliler不同意,符合市場預期

Ileft iLeftReference = getILeft(); 
MoveableOject mObj = iLeftReference; // same error 
2

,你正在觀察有沒有關係明確的實施ILeft錯誤。其實這是因爲assignment compatibility。 我們只能將更多的派生對象分配給派生較少的對象,而不是相反。

你不能做:

MoveableOject moWithErrorObject = (ILeft) new MoveableOject(); 

隨着MoveableOject更衍生比它的父ILeft

你可以得到一些細節here

相關問題