0

たとえば、抽象クラス 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

そのようなことは可能ですか?もしそうなら、どうすればそれを行うことができますか?

4

1 に答える 1