【发布时间】:2018-06-03 22:38:57
【问题描述】:
我需要一个接口对象IMyInterface obj;,它可以吞下从它继承的所有类对象,因为我的示例代码运行良好,但在内部我需要实现我不需要的函数,因为IMyInterface 需要它,我尝试这两种方法都失败了:
创建
virtual class MethodThatNotBelongToUsAll{}并尝试class ClassA_wrap : ClassA, MethodThatNotBelongToUsAll, IMyInterface但收到错误class 'ClassA_wrap' cannot have multiple base classes将
interface IMyInterface更改为virtual class IMyInterface{}但obj = new ClassA_wrap();行显示错误cannot implicitly convert type "ClassA_wrap" to "IMyInterface"
谁能帮我解决这个问题?谢谢!
interface IMyInterface
{
int Foo0 { get; } //ClassA,B,C method
int FooWrap(int F); //ClassA_wrap,B_wrap,C_wrap method
int FooA(int F); // ClassA method
int FooB(int F); // ClassB method
int FooC(int F); // ClassC method
}
class ClassA //Base Class, can't edit
{
public int Foo0{ get { return 1; } }
public int FooA(int F) { return F; }
}
class ClassB //Base Class, can't edit
{
public int Foo0 { get { return 2; } }
public int FooB(int F) { return F; }
}
class ClassC //Base Class, can't edit
{
public int Foo0 { get { return 3; } }
public int FooC(int F) { return F; }
}
class ClassA_wrap : ClassA, IMyInterface
{
public int FooB(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooC(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooWrap(int F)
{
return FooA(F)*10+1;
}
}
class ClassB_wrap : ClassB, IMyInterface
{
public int FooA(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooC(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooWrap(int F)
{
return FooB(F)*20+2;
}
}
class ClassC_wrap : ClassC, IMyInterface
{
public int FooA(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooB(int F) { return -1; } // I want to get rid of this line, but Interface require to imp this...
public int FooWrap(int F)
{
return FooC(F)*30+3;
}
}
class MainClass
{
static void Main()
{
IMyInterface obj; //I need IMyInterface object that can swallow all three classes depend on flag
int flag = 2; // or 1 or 3
if(flag==1)
obj = new ClassA_wrap();
else if(flag==2)
obj = new ClassB_wrap();
else
obj = new ClassC_wrap();
//-----------------------------------------
Console.WriteLine( obj.Foo0);
//-----------------------------------------
if(obj is ClassA_wrap)
Console.WriteLine(obj.FooA(11));
if (obj is ClassB_wrap)
Console.WriteLine(obj.FooB(22));
if (obj is ClassC_wrap)
Console.WriteLine(obj.FooC(33));
//-----------------------------------------
Console.WriteLine(obj.FooWrap(1));
Console.Read();
}
}
【问题讨论】:
-
如果你的接口有太多的方法来匹配你的类。为什么不将接口拆分为 2 个单独的接口。您可以从任意数量的接口继承。
-
更好的模式是创建一个接口,其中只包含所有子类所需的方法,而其他接口则包含特定于类的方法。每个子类都根据需要继承基接口和其他接口。
标签: c# inheritance interface virtual