簡體   English   中英

C# class 繼承自接口並且類型繼承自接口類型方法時出現錯誤 CS0738

[英]C# Error CS0738 when class inherits from interface and with type that inherits from interfce type method

當 class 實現一個接口時,我得到了 CS0738,並且接口有一個方法,具有返回類型接口。

而在 class 中,返回類型是一個實現返回類型接口的結構。

簡單地說,這段代碼顯示了問題:

public interface IGame
{
    IPlayer WhoWin();
}

public interface IPlayer
{
    int ID { get; }
}

在 class 中:

public class MyGame : IGame
{
    // ERROR CS0738
    public MyPlayer WhoWin()
    {
        // ...
        return null;
    }
}

public class MyPlayer : IPlayer
{
    public int ID 
    {
        get
        {
            return ColorTranslator.ToWin32(Color);
        }
    }
    public Color Color;
}

我應該怎么辦? 我該如何解決這個問題?

MyGame MyPlayer WhoWinIPlayer ,然后它應該可以工作。

public class MyGame : IGame
{
    // CHANGE THIS TO IPlayer like here:
    public IPlayer WhoWin()
    {
        // ...
        return null;
    }
}

public class MyPlayer : IPlayer
{
    public int ID 
    {
        get
        {
            return ColorTranslator.ToWin32(Color);
        }
    }
    public Color Color;
}

您可以制作IGame通用接口並應用where T: IPlayer約束

public interface IGame<out T> where T : IPlayer
{
    T WhoWin();
}

然后像這樣實現它

public class MyGame : IGame<MyPlayer>
{
    public MyPlayer WhoWin()
    {
        // ...
        return null;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM