Home > other >  Generalization of a class constructor with interface (.Net Framework 4.8)
Generalization of a class constructor with interface (.Net Framework 4.8)

Time:12-30

Simplifying the question, I have these 2 functions

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

and

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

Is it possible to generalize these functions?

My main problem is the different inputs, but putting that aside, is it possible with interfaces?

Something like

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

CodePudding user response:

Factory method/interface seem to be what you are looking for:

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

  •  Tags:  
  • c#
  • Related