在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
這與顯式接口無關。 'MoveableObject'繼承自'ILeft',而不是相反。 – Rhumborl
顯式實現允許您的方法僅在作爲接口本身進行投射時纔可訪問。在這種情況下。 – CodeNotFound
任何人都可以對編輯後的代碼發表評論嗎?這是我的初衷,想問這個問題。謝謝。 – RotatingWheel