Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
避免在多种类似方法中重复代码(C#)_C#_Design Patterns_Generics_Delegates - Fatal编程技术网

避免在多种类似方法中重复代码(C#)

避免在多种类似方法中重复代码(C#),c#,design-patterns,generics,delegates,C#,Design Patterns,Generics,Delegates,大家好 在C#中,我有一些非常类似的方法(可能还会有几十个)。它们都建立在几乎相同的模式上: ResultObjectType MethodX(...input parameters of various types...) { nesting preparation code here... { { resultObject = ExternalClass.GetResultForMethodX(input parameters of MethodX); }

大家好

在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、准备代码、结果处理代码

不同部分:要调用的ExternalClass方法、输入参数集(输入参数的数量及其类型)

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

我试图避免重复类似代码的所有代码块,如下所示:

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;
}

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

下面是一个使用一般委托的示例:

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;
}
int方法(int某物,int其他)
{
返回UniversalMethod(()=>GetResultForMethodY(something,other));
}
string MethodX(string某物)
{
返回UniversalMethod(()=>GetResultForMethodX(something));
}
T通用方法(函数取数器)
{
结果对象;
//嵌套准备代码在这里。。。
{
resultObject=fetcher();
}
//在此处嵌套结果处理代码。。。
返回结果对象;
}
如果ResultObjectType始终相同,则可以删除所有重复/相同的部分:ResultObjectType、准备代码、结果处理代码

你应该集中精力使这部分尽可能地隔离


另一种方法是代码生成。

您的预处理和后处理代码是否完全相同,以及它们是否围绕输入参数进行任何计算?所有方法中的输入参数是否在类型和顺序上相同>这正是我要查找的。非常感谢你,波格斯!