【问题标题】:An abstract class inheriting an interface, how to implement explicit interface?继承接口的抽象类,如何实现显式接口?
【发布时间】:2013-09-05 11:24:15
【问题描述】:

我创建了两个接口I1I2。我已将这两个接口继承到一个抽象类。
接口I1I2有相同的方法Add(),如何在派生类中使用显式接口实现呢?

代码片段

using System;

interface I1
{
    void Add(int _fn, int _sn);
    void Prod(int _fn, int _sn);
    void Sub(int _fn, int _sn);
}

interface I2
{
    void Add(int _fn, int _sn);
}

abstract class Simple: I2, I1
{
    public abstract void Add(int _fn, int _sn);
    public abstract void Prod(int _fn, int _sn);
    public abstract void Sub(int _fn, int _sn);
    void I2.Add(int _fn, int _sn);
}


class Program : Simple
{
    public override void Add(int _fn, int _sn)
    {
        Console.WriteLine(_fn+_sn);
    }

    public override void Prod(int _fn, int _sn)
    {
        Console.WriteLine(_fn * _sn);
    }

    public override void Sub(int _fn, int _sn)
    {
        Console.WriteLine(_fn - _sn);
    }

    void Add(int _fn, int _sn)
    {
        Console.WriteLine(_fn % _sn);
    }

    static void Main()
    {
        I1 inter = new Program();

        inter.Add(2, 3);
        inter.Prod(2, 4);
        inter.Sub(3,5);
    }
}

我收到一个错误

Type 'Program' already defines a member called 'Add' with the same parameter types

谁能帮我解决这个问题。提前致谢。

【问题讨论】:

  • 使用 两个 Add() 方法做完全相同的事情没有任何意义。抽象的 Simple.Add() 已经实现了 I1.Add 和 I2.Add。因此,只需摆脱显式接口实现和不需要的 Program.Add()。并且编写适当的代码,抽象方法不能有主体。
  • 我已经编辑了我的代码,以便让您更好地了解我想要的内容。
  • 如果你在抽象简单类中添加正文,代码编译得很好。没有您提供的错误。

标签: .net c#-4.0 inheritance interface


【解决方案1】:

使用不同名称的抽象方法:

abstract class Simple: I2, I1
{
    public abstract void Add(int _fn, int _sn);
    public abstract void Prod(int _fn, int _sn);
    public abstract void Sub(int _fn, int _sn);
    void I2.Add(int _fn, int _sn)
    {
        AddInternal(_fn, _sn);
    }

    protected abstract void AddInternal(int _fn, int _sn);
}

并在具体类中覆盖它:

protected override void AddInternal(int _fn, int _sn)
{
    Console.WriteLine(_fn + _sn);
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-11-03
  • 2018-04-05
  • 2012-04-11
  • 2012-07-15
  • 2011-09-16
  • 1970-01-01
  • 2013-01-09
  • 2011-02-17
相关资源
最近更新 更多