C# 当一个类需要不同的结构时,如何创建通用行为

C# 当一个类需要不同的结构时,如何创建通用行为,c#,design-patterns,C#,Design Patterns,我得到了一些C#类,它们带有一个方法,可以创建我需要的字符串。两个班的做法相同,但一个班的做法不同: 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)

我得到了一些C#类,它们带有一个方法,可以创建我需要的字符串。两个班的做法相同,但一个班的做法不同:

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
        }
     }
问题是A类和B类实际上只有一个
Str1
Str2
,而C类可以有几个。由于它们来自同一个基类,用户将期望使用相同的接口。
您认为解决这个问题的一个好的实现是什么?

因此,更简单、更具体地说,您的问题是,对于方法
getAction()
,您需要相同的返回类型,但是类a和类B需要
StringInfo
作为返回类型,而类C需要它作为
List

解决方案是使用

公共类基
{
公共摘要T GetAction(输出字符串res);
}
公共A类:基本类
{
公共重写StringInfo GetAction(输出字符串资源)
{
//实施
}
}
公共C类:基础
{
公共覆盖列表GetAction(输出字符串res)
{
//实施
}
}

最后,如果您想使
StringInfo
更具可扩展性,可以对该类使用抽象。如果您希望将来有不同的行为,那么为
toString()
methodos添加不同的逻辑会有所帮助。

对于名为
C
str1
的东西,很难给出建议。您能将它们重命名为更有意义的名称吗?同时,我建议将Str1设置为
IEnumerable
public StringsInfoClass
{
    public string Str1 { get; set; }
    public string Str2 { get; set; }
    ...
    public string ToString()
    { 
        return Str1 + Str2;
    }
}
public class Base<T> 
{
    public abstract T GetAction(out string res);
}

public class A : Base<StringInfo> 
{
   public override StringInfo GetAction(out string res)
   {
      //implementation
   }
}

public class C : Base<List<StringInfo>> 
{
   public override List<StringInfo> GetAction(out string res)
   {
      //implementation
   }
}