dimanche 17 juin 2018

How to make a common behavior when a single class needs different structure

I got some C# classes with a method which creates a string I need. 2 classes does it the same but 1 class does it differently:

public class Base 
{
    public abstract bool GetAction(out string res);
}

// There is another class B which does the same
public class A : Base 
{
    public override bool GetAction(out string res)
    {
       ...
       string str1 = some logic to get a string needed
       string str2 = some logic to get another string needed
       res = str1 + str2;
       ...
    }
}

public class C : Base
{
    List<Configs> configs;
    ...

    public override bool GetAction(out string res)
    {
       ...
       for(int i = 0 ; i < configs.size(); i++)
       {
           string str1 = some logic to get string based on configs[i].cfgString;
           string str2 = some logic to get another string based on configs[i].cfgString;
           res = res + configs[i].cfgString + str1 + str2; //immutable string is not the issue here so please ignore it
        }
     }

Now there's a need to get the str1 and str2 by itself.

I started making a return class instead of the bool of the GetAction method like this:

public StringsInfoClass
{
    public string Str1 { get; set; }
    public string Str2 { get; set; }
    ...
    public string ToString()
    { 
        return Str1 + Str2;
    }
}

The problem is that classes A and B has indeed only a single Str1 and Str2 while class C can have several of them. And since they are deriving from the same base class, the user will expect the same interface. What do you believe a good implementation for this problem here could be?

Aucun commentaire:

Enregistrer un commentaire