【问题标题】:BaseClass cannot implement interface.variable because it does not have the matching return typeBaseClass 无法实现 interface.variable,因为它没有匹配的返回类型
【发布时间】:2017-12-28 08:40:17
【问题描述】:

编辑:已解决。我有时是个白痴。请参阅下面的自我回答...

我正在使用接口和多态性处理以下 C# .Net4.5 代码


public interface IFile
{
    List<string> Contents {get;set;}
}

public class File : IFile
{
    public List<string> Contents {get;set;}
}

public interface ICommandFile : IFile
{
    new List<ICommandFileLine> Contents {get;set;} /*ICommandFileLine is defined in the code as well, but I don't believe this is pertinent to the issue I am having.*/
}

public class CommandFile : File, ICommandFile
{
    public new List<ICommandFileLine> Contents {get;set;}
}

当我尝试执行上述操作时,预编译器会抱怨:

CommandFile 没有实现接口成员 “ICommandFile.Contents”。 'File.Contents' 无法实现 “ICommandFile.Contents”,因为它没有匹配的返回 “列表[ICommandFileLine]”的类型

接口成员“List ICommandFile.Contents”不是 实施。

我不明白。我用的是new关键字,这应该说明我想封装基类并定义新的变量类型吧?

【问题讨论】:

    标签: c# inheritance interface polymorphism encapsulation


    【解决方案1】:

    尝试通用接口 - IFile&lt;T&gt;。然后ICommandFile 实现IFile&lt;CommandLine&gt;. 明白了吗?

    【讨论】:

      【解决方案2】:

      接口成员实现不应像在 CommandFile 类中那样标记为“新”),这意味着实现类中的成员与从接口继承的成员无关。

      【讨论】:

        【解决方案3】:

        我在发帖后不到 5 分钟就意识到自己做错了什么:

        List[ICommandFile] 内容 EQUALS!? 不,{get;set;}

        改变:

        新列表[ICommandFileLine] 内容 = 新 ListICommandFileLine;

        在我的本地代码中:

        新列表[ICommandFileLine] 内容 {get;set;}

        好尴尬……

        对于实现接口和时常犯这些错误,我还是比较陌生。

        【讨论】:

        • 如果你足够好回答,那么你就足够格式化了:)
        • 嗯,我的意思是,我确实格式化了我的 OP 和我的回复,以及我可以给这个网站的时髦标记。如果这对你很重要,而且你已经证明你有能力,那就做我的客人吧。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-09
        相关资源
        最近更新 更多