接口中的 C# 构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1686157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# constructor in interface
提问by Toto
I know that you can't have a constructor in an interface, but here is what I want to do:
我知道接口中不能有构造函数,但这是我想要做的:
interface ISomething
{
void FillWithDataRow(DataRow)
}
class FooClass<T> where T : ISomething , new()
{
void BarMethod(DataRow row)
{
T t = new T()
t.FillWithDataRow(row);
}
}
I would really like to replace ISomething
's FillWithDataRow
method with a constructor somehow.
我真的很想以某种方式用构造函数替换ISomething
'sFillWithDataRow
方法。
That way, my member class could implement the interface and still be readonly (it can't with the FillWithDataRow
method).
这样,我的成员类可以实现接口并且仍然是只读的(它不能使用FillWithDataRow
方法)。
Does anyone have a pattern that will do what I want?
有没有人有一种模式可以做我想做的事?
采纳答案by Jon Skeet
(I should have checked first, but I'm tired - this is mostly a duplicate.)
(我应该先检查一下,但我累了 - 这主要是重复的。)
Either have a factory interface, or pass a Func<DataRow, T>
into your constructor. (They're mostly equivalent, really. The interface is probably better for Dependency Injection whereas the delegate is less fussy.)
要么有一个工厂接口,要么将 a 传递给Func<DataRow, T>
您的构造函数。(它们几乎是等效的,真的。接口可能更适合依赖注入,而委托则不那么挑剔。)
For example:
例如:
interface ISomething
{
// Normal stuff - I assume you still need the interface
}
class Something : ISomething
{
internal Something(DataRow row)
{
// ...
}
}
class FooClass<T> where T : ISomething , new()
{
private readonly Func<DataRow, T> factory;
internal FooClass(Func<DataRow, T> factory)
{
this.factory = factory;
}
void BarMethod(DataRow row)
{
T t = factory(row);
}
}
...
FooClass<Something> x = new FooClass<Something>(row => new Something(row));
回答by NDM
use an abstract class instead?
改用抽象类?
you can also have your abstract class implement an interface if you want...
如果你愿意,你也可以让你的抽象类实现一个接口......
interface IFillable<T> {
void FillWith(T);
}
abstract class FooClass : IFillable<DataRow> {
public void FooClass(DataRow row){
FillWith(row);
}
protected void FillWith(DataRow row);
}