本文介绍了定义构造函数签名的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很奇怪,这是我第一次碰到这个问题,但是:



如何在C#界面中定义构造函数?



编辑

有些人想要一个例子(这是一个自由时间项目,所以是的,这是一个游戏)



IDrawable

+更新

+绘制



为了能够更新(检查屏幕边缘等)并绘制自己,它总是需要一个 GraphicsDeviceManager 。所以我想确保对象有一个引用它。这将属于构造函数。



现在我写下来,我想我在这里实现的是 IObservable 并且 GraphicsDeviceManager 应该接受 IDrawable ...
看来要么我没有得到XNA框架,或框架没有被很好地考虑。



编辑

似乎有一些混乱我在一个接口的上下文中的构造函数的定义。一个接口确实不能被实例化,所以不需要一个构造函数。我想定义的是对构造函数的签名。完全像一个接口可以定义某个方法的签名,接口可以定义构造函数的签名。

解决方案

't。



在一篇博文中,我建议了



有一点,如果你可以在接口中定义一个构造函数,你可以在导出类时遇到麻烦:

  public class Foo:IParameterlessConstructor 
{
public Foo /根据界面
{
}
}

public class Bar:Foo
{
// Yikes!我们现在没有一个无参数的构造函数...
public Bar(int x)
{
}
}
pre>

It's weird that this is the first time I've bumped into this problem, but:

How do you define a constructor in a C# interface?

Edit
Some people wanted an example (it's a free time project, so yes, it's a game)

IDrawable
+Update
+Draw

To be able to Update (check for edge of screen etc) and draw itself it will always need a GraphicsDeviceManager. So I want to make sure the object has a reference to it. This would belong in the constructor.

Now that I wrote this down I think what I'm implementing here is IObservable and the GraphicsDeviceManager should take the IDrawable... It seems either I don't get the XNA framework, or the framework is not thought out very well.

Edit
There seems to be some confusion about my definition of constructor in the context of an interface. An interface can indeed not be instantiated so doesn't need a constructor. What I wanted to define was a signature to a constructor. Exactly like an interface can define a signature of a certain method, the interface could define the signature of a constructor.

解决方案

You can't. It's occasionally a pain, but you wouldn't be able to call it using normal techniques anyway.

In a blog post I've suggested static interfaces which would only be usable in generic type constraints - but could be really handy, IMO.

One point about if you could define a constructor within an interface, you'd have trouble deriving classes:

public class Foo : IParameterlessConstructor
{
    public Foo() // As per the interface
    {
    }
}

public class Bar : Foo
{
    // Yikes! We now don't have a parameterless constructor...
    public Bar(int x)
    {
    }
}

这篇关于定义构造函数签名的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:33