将接口实现作为组件添加到游戏对象

Add interface implementation as a component to a gameobject

使用依赖注入,你可以有一个相同的接口代表不同的 classes,因为 class 实现可以绑定到依赖容器,按照在绑定阶段的绑定阶段定义.我的问题是,一旦完成各自的绑定,如果实现是单一行为,是否有机会将界面作为组件添加到游戏对象。

为什么我想这样做的故事很长,所以可以假设这个必要性刚刚出现:)。

找一些伪代码加深理解:

public interface IFoo {
    //...
}

public class FooIplementtation1: MonoBehaviour {
    //....
}

public class FooIplementtation2: MonoBehaviour {
    //....
}

if (someCondition) {
    Container.Bind<IFoo >().To<FooIplementtation1>();
} else {
    Container.Bind<IFoo >().To<FooIplementtation2>()
}

我打算做的是:

//Error. Interface type cannot be added as component.
someTransform.gameObject.AddComponent<IFoo>();

但是我得到错误:

The type IFoo cannot be used as type parameter 'T' in the generic or method GameObject.AddComponent<T>().

方法签名是:

public T AddComponent<T>() where T : Component;

Si 我试图让我的界面继承自 Monobehaviour 并形成 Component 但那没有用。

知道这是否可行吗?如果可行,怎么做?

GameObject.AddComponent 文档说明

Adds a component class named className to the game object.

组件类型应该是class,不能是struct或interface。 接口只是一个约定,class 必须实现给定的接口功能和属性。您隐藏了为什么要为您的代码使用接口,但如果可能的话,请创建一个基础 class,其中包含所有 class 共享的所有内容。简而言之使用Polymorphism。从 monobehaviour 继承基础class,你可以做你想做的事。

也认为接口根本没有数据。它们只是空的实现,它的哪一部分可以成为对象的组件?他们只是让编码更容易而已。也许,您想查看 C# Design Patterns.