C#中如何继承两个或多个具有相同方法名的接口,并且派生类应该进一步继承到另一个类中
c#
我们如何在类中实现两个或多个具有相同方法名称的接口,并且派生类应该进一步继承到具有相同方法的新类中。
using System;
interface A
{
void Hello();
}
interface B
{
void Hello();
}
class Test : A, B
{
void A.Hello()
{
Console.WriteLine("Test Hello-A");
}
void B.Hello()
{
Console.WriteLine("Test Hello-B");
}
}
class Demo : Test {
//what will be the code to override Hello method
}
public class MainClass
{
public static void Main()
{
//How can we access the Hello method of Test & Demo class
}
}
回答
使用显式接口实现时有一些限制,因为方法不能是virtual. 但是您可以通过创建更多可以是虚拟的方法然后覆盖它们来解决此问题。
我对这段代码不太满意,但它完全回答了你的问题。
using System;
interface A
{
void Hello();
}
interface B
{
void Hello();
}
class Test : A, B
{
public virtual void HelloA()
{
Console.WriteLine("Test Hello-A");
}
public virtual void HelloB()
{
Console.WriteLine("Test Hello-A");
}
void A.Hello()
{
this.HelloA();
}
void B.Hello()
{
this.HelloB();
}
}
class Demo : Test
{
//what will be the code to override Hello method
public override void HelloA()
{
}
public override void HelloB()
{
}
}
public class MainClass
{
public static void Main()
{
//How can we access the Hello method of Test & Demo class
Test test = new();
test.HelloA();
test.HelloB();
Demo demo = new();
demo.HelloA();
demo.HelloB();
// Another option will be to call it using the interfaces:
List<A> itemsA = new();
itemsA.Add(test);
itemsA.Add(demo);
foreach (A itemA in itemsA)
{
itemA.Hello();
}
List<B> itemsB = new();
itemsB.Add(test);
itemsB.Add(demo);
foreach (B itemB in itemsB)
{
itemB.Hello();
}
}
}
THE END
二维码