【问题标题】:Avoiding repetitive code in multiple similar methods (C#)避免在多个类似方法中重复代码 (C#)
【发布时间】:2011-05-05 02:38:38
【问题描述】:

大家好!

我在 C# 中有一组(可能还有几十个)非常相似的方法。它们都建立在几乎相同的模式上:

ResultObjectType MethodX(...input parameters of various types...)
{
  nesting preparation code here...
  {
    {
      resultObject = ExternalClass.GetResultForMethodX(input parameters of MethodX);
    }
  }
  nesting result processing code here ...
  return resultObject;
}

重复/相同部分:ResultObjectType,准备代码,结果处理代码

不同部分:要调用的外部类方法,输入参数集(输入参数的数量,它们的类型)。

重要提示:我无法控制方法签名 - 无法更改它们。

我试图避免使用类似这样的代码重复所有类似代码块:

ResultObjectType MethodX(...input parameters of various types...)
{
    return  UniversalMethod( 
                   new ExternalMethodDelegate(ExternalClass.GetResultForMethodX),
                   input parameters of MethodX...);
}

ResultObjectType UniversalMethod (Delegate d, input parameters of various types...)
{
    nesting preparation code...
    {
        {
           resultObject = 
              (d as ExternalMethodDelegate)(same input parameters as above);
        }
    }
    nesting result processing code...
    return resultObject;
}

到目前为止,我只设法使其以这种方式工作,以防所有参数在编码时具有相同的已知类型。经过多次尝试用通用代表解决这个问题后,我开始认为这是不可能实现的。即使我的代码编译,它在运行时也不起作用。有接盘侠吗?提前感谢您的帮助!

【问题讨论】:

  • 您的预处理和后处理代码是否完全相同,它们是否围绕输入参数进行任何计算?所有方法的输入参数在类型和顺序上是否相同>

标签: c# design-patterns generics delegates


【解决方案1】:

这是一个使用泛型委托的示例:

int MethodY(int something, int other)
{
    return UniversalMethod(() => GetResultForMethodY(something, other));
}

string MethodX(string something)
{
    return UniversalMethod(() => GetResultForMethodX(something));
}

T UniversalMethod<T>(Func<T> fetcher)
{
    T resultObject;
    //nesting preparation code here...
    {
        resultObject = fetcher();
    }
    //nesting result processing code here ...
    return resultObject;
}

如果 ResultObjectType 始终相同,则可以删除所有 Ts。

【讨论】:

  • 这正是我想要的。非常感谢波格斯!
【解决方案2】:

重复/相同部分:ResultObjectType、准备代码、结果处理代码。

您应该集中精力使这些部分尽可能孤立。

另一种方法是代码生成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 2022-06-10
    • 2021-07-08
    • 1970-01-01
    相关资源
    最近更新 更多