たとえば、抽象クラス 2 インターフェースがあるとします。
public abstract class Entity
{
public abstract void Interact(Entity entity);
}
public interface IFoo
{
void DoFoo();
}
public interface IBar
{
void DoBar();
}
そして今、これらのインターフェースを実装する 2 つのクラスがあるとします。
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
そのようなことは可能ですか?もしそうなら、どうすればそれを行うことができますか?