【发布时间】:2013-10-23 09:25:11
【问题描述】:
我知道这听起来微不足道,但是当我将 A 变量传递给需要 IMyIntercace 的函数时,是否有可能返回 b 字段?然后我不必在 A 类中实现 Hello() 函数,而是将 b 作为 IMyInterface 返回。
interface IMyInterface
{
void Hello();
}
class A : IMyInterface
{
B b = new B();
}
class B : IMyInterface
{
public void Hello()
{
Console.WriteLine("Hello");
}
}
class Program
{
static void foo(IMyInterface myInterface)
{
myInterface.Hello();
}
static void Main(string[] args)
{
A someVariable = new A();
foo(someVariable);
}
}
我想这是做不到的,但是有什么设计模式或技巧可以做到吗?
编辑
我不想导出 A 的原因是因为也许我想这样做
class A : IMyInterface
{
B b = new B();
B b2 = new B();
IMyInterface bPointer;
}
然后我可以根据某些情况指向 b 之一
【问题讨论】:
-
你为什么有这样的需求?设计将取决于您想要实现什么?
-
为什么不
class A : B?
标签: c# design-patterns interface