这是我第一次碰到这个问题,这很奇怪,但是:
如何在C#接口中定义构造函数?
编辑
有些人想要一个例子(这是一个空闲时间项目,所以是的,这是一个游戏)
IDrawable
+ Update
+ Draw
为了能够更新(检查屏幕边缘等)并绘制自己,它总是需要一个GraphicsDeviceManager.所以我想确保对象有引用它.这将属于构造函数.
现在,我写下来我想我在这里实施的IObservable和GraphicsDeviceManager应该采取的IDrawable......看来要么我不明白的XNA框架或框架不是想出来的非常好.
编辑
在接口的上下文中,我对构造函数的定义似乎有些混乱.实际上不能实例化接口,因此不需要构造函数.我想要定义的是构造函数的签名.正如接口可以定义某个方法的签名,接口可以定义构造函数的签名.
我知道在接口中定义构造函数是不可能的.但我想知道为什么,因为我觉得它可能非常有用.
因此,您可以确保为此接口的每个实现定义了类中的某些字段.
例如,考虑以下消息类:
public class MyMessage {
public MyMessage(String receiver) {
this.receiver = receiver;
}
private String receiver;
public void send() {
//some implementation for sending the mssage to the receiver
}
}
Run Code Online (Sandbox Code Playgroud)
如果为这个类定义一个接口,以便我可以有更多的类来实现消息接口,那么我只能定义send方法而不是构造函数.那么我怎样才能确保这个类的每个实现都有一个接收器集呢?如果我使用像setReceiver(String receiver)我这样的方法,我不能确定这个方法是否真的被调用.在构造函数中,我可以确保它.
如何为具有接口成员变量的类编写复制构造函数?
例如:
public class House{
// IAnimal is an interface
IAnimal pet;
public House(IAnimal pet){
this.pet = pet;
}
// my (non-working) attempt at a copy constructor
public House(House houseIn){
// The following line doesn't work because IAnimal (an interface) doesn't
// have a copy constructor
this.pet = new IAnimal(houseIn.pet);
}
}
Run Code Online (Sandbox Code Playgroud)
我被迫有一个混凝土Animal吗?如果是这样的话,似乎重复使用课程与狗的房子与猫的房子变得错综复杂!
根据为什么我们不允许在接口中指定构造函数的答案?,
因为接口描述了行为.构造函数不是行为.如何构建对象是一个实现细节.
如果interface描述行为,为什么interface允许声明状态?
public interface IStateBag
{
object State { get; }
}
Run Code Online (Sandbox Code Playgroud)