【发布时间】:2013-09-05 11:24:15
【问题描述】:
我创建了两个接口I1和I2。我已将这两个接口继承到一个抽象类。
接口I1和I2有相同的方法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