类构造函数的泛化与接口(.. Net Framework 4.8)



简化问题,我有这两个函数

private void ReadFilesCommon(List<string> input)
{
foreach (string entry in input)
{
new Class1(entry, entry.length);
}
}

private void ReadFilesCommon2(List<string> input)
{
foreach (string entry in input)
{
new Class2(entry);
}
}

有可能推广这些函数吗?

我的主要问题是不同的输入,但把它放在一边,有可能用接口吗?

之类的
private void ReadFilesCommon2(IClass Class)
{
foreach ()
{
new Class(input1);
}
}

工厂方法/接口似乎是你正在寻找的:

private void ReadFiles<T>(List<string> input, Func<string, T> creator)
{
foreach (string entry in input)
{
var item = creator(entry);
}
}
// and replace your functions with:
ReadFiles(input, s => new Class1(s)); // ReadFilesCommon
ReadFiles(input, s => new Class2(s, s.Length)); // ReadFilesCommon1

最新更新