假设,我有一个抽象类 2 接口:
public abstract class Entity
{
public abstract void Interact(Entity entity);
}
public interface IFoo
{
void DoFoo();
}
public interface IBar
{
void DoBar();
}
现在,假设我有两个实现这些接口的类:
public class Foo : Entity, IFoo
{
public override void Interact(Entity entity)
{
// do something with entity...
}
public void DoFoo()
{
// Do foo stuff here..
}
}
public class Bar : Entity, IBar
{
public override void Interact(Entity entity)
{
// do something with obj..
}
public void DoBar()
{
// Do bar stuff here..
}
}
现在的问题是,由于这些类实现了相同的抽象类(Entity
),因此可以Bar
与之交互,Foo
反之亦然,如下所示:
var foo = new Foo();
var bar = new Bar();
foo.Interact(bar); // OK!
bar.Interact(foo); // OK too!
但是现在,我希望Foo
只能与另一个实例交互IFoo
并在它尝试与实例交互时给出编译时错误Bar
,同样的规则也应该适用Bar
。所以应该是这样的..
var foo = new Foo();
var anotherFoo = new Foo();
var bar = new Bar();
foo.Interact(anotherFoo); // OK!
foo.Interact(bar); // give compile time error
bar.Interact(foo); // this one should give compile time error too
有可能做这样的事情吗?如果是这样,我该怎么做?