Tot*_*oto 5 c# generics interface
我知道你不能在界面中有一个构造函数,但这是我想要做的:
interface ISomething
{
void FillWithDataRow(DataRow)
}
class FooClass<T> where T : ISomething , new()
{
void BarMethod(DataRow row)
{
T t = new T()
t.FillWithDataRow(row);
}
}
Run Code Online (Sandbox Code Playgroud)
我真的想以某种方式用构造函数替换ISomething's FillWithDataRow方法.
这样,我的成员类可以实现接口,仍然是只读(它不能与FillWithDataRow方法).
有没有人有一个可以做我想要的模式?
使用抽象类代替?
你也可以让你的抽象类实现一个接口,如果你想...
interface IFillable<T> {
void FillWith(T);
}
abstract class FooClass : IFillable<DataRow> {
public void FooClass(DataRow row){
FillWith(row);
}
protected void FillWith(DataRow row);
}
Run Code Online (Sandbox Code Playgroud)
(我应该先检查一下,但我累了 - 这主要是重复的。)
要么有一个工厂接口,要么将 a 传递给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));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26665 次 |
| 最近记录: |