0

假设,我有一个抽象类 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

有可能做这样的事情吗?如果是这样,我该怎么做?

4

1 回答 1

2

你在这里混淆了一些元素

Entity 与 IFoo 或 IBar 没有关系
Foo 与 Entity 和 IFoo 有关系 Bat 与 Entity 和 IBar 有关系

因此,如果您只想与 IFoo 交互,则需要将 IFoo 指定为父级而不是实体

public class Foo : Entity, IFoo
{
    public void Interact(IFoo entity)
    {
        // do something with entity...
    }

    public void DoFoo()
    {
       // Do foo stuff here..
    }
}

public class Bar : Entity, IBar
{
    public void Interact(IBar entity)
    {
        // do something with obj..
    }

    public void DoBar()
    {
       // Do bar stuff here..
    }
}

由于交互的行为并非由其所有子级共享,因此交互不属于父级

你可以用泛型来解决这个问题

public abstract class Entity<T>
 where T:Entity
{
    void Interact(T entity);
}

这将允许您将 foo 声明为

public class Foo : Entity<Foo>, IFoo
{
    public override void Interact(Foo entity)
    {
        // do something with entity...
    }

    public void DoFoo()
    {
       // Do foo stuff here..
    }
}
于 2016-03-18T15:08:19.293 回答