【问题标题】:C# constructor in interface接口中的 C# 构造函数
【发布时间】:2010-12-13 18:10:09
【问题描述】:
我知道接口中不能有构造函数,但这是我想做的:
interface ISomething
{
void FillWithDataRow(DataRow)
}
class FooClass<T> where T : ISomething , new()
{
void BarMethod(DataRow row)
{
T t = new T()
t.FillWithDataRow(row);
}
}
我真的很想用构造函数替换ISomething 的FillWithDataRow 方法。
这样,我的成员类可以实现接口并且仍然是只读的(不能使用FillWithDataRow 方法)。
有没有人可以做我想做的事情?
【问题讨论】:
标签:
c#
interface
generics
【解决方案1】:
改用抽象类?
如果你愿意,你也可以让你的抽象类实现一个接口...
interface IFillable<T> {
void FillWith(T);
}
abstract class FooClass : IFillable<DataRow> {
public void FooClass(DataRow row){
FillWith(row);
}
protected void FillWith(DataRow row);
}
【解决方案2】:
(我应该先检查一下,但我累了 - 这主要是duplicate。)
要么有一个工厂接口,要么将Func<DataRow, T> 传递给你的构造函数。 (实际上,它们基本上是等价的。接口可能更适合依赖注入,而委托则不那么挑剔。)
例如:
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));