很奇怪,这是我第一次遇到这个问题,但是:
如何在c#接口中定义构造函数?
编辑
有些人想要一个例子(这是一个自由时间项目,所以是的,这是一个游戏)
IDrawable
+更新
+画
为了能够更新(检查屏幕边缘等)和绘制本身,它总是需要一个GraphicsDeviceManager。我想确保对象有一个指向它的引用。这将属于构造函数。
现在我把这个写下来了,我想我在这里实现的是IObservable GraphicsDeviceManager应该采用IDrawable。
似乎不是我没有理解XNA框架,就是这个框架没有考虑得很好。
编辑
我在接口上下文中对构造函数的定义似乎有些混乱。接口确实不能被实例化,因此不需要构造函数。我想定义的是构造函数的签名。就像接口可以定义某个方法的签名一样,接口也可以定义构造函数的签名。
接口的目的是强制某个对象签名。它不应该明确地关心对象内部如何工作。因此,从概念的角度来看,接口中的构造函数并没有真正的意义。
不过也有一些替代方案:
Create an abstract class that acts as a minimal default implementation.
That class should have the constructors you expect implementing classes
to have.
If you don't mind the overkill, use the AbstractFactory pattern and
declare a method in the factory class interface that has the required
signatures.
Pass the GraphicsDeviceManager as a parameter to the Update and Draw methods.
Use a Compositional Object Oriented Programming framework to pass the GraphicsDeviceManager into the part of the object that requires it. This is a pretty experimental solution in my opinion.
你描述的情况一般来说不容易处理。业务应用程序中需要访问数据库的实体也有类似的情况。