避免重复的代码在多个类似的方法(C#) [英] Avoiding repetitive code in multiple similar methods (C#)

查看:574
本文介绍了避免重复的代码在多个类似的方法(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问大家!

我在C#中有一些非常类似的方法(可能会有几十个)。它们都基于几乎相同的模式:

I have a set of a few (and potentially will have dozens more) of very similar methods in C#. They all built on almost identical pattern:

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

Repeating/identical parts: ResultObjectType, preparation code, result processing code.

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

Different parts: ExternalClass method to call, input parameter set (number of input parameters, their types).

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

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

I am trying to avoid repeating all blocks of similar code with something like this:

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

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

So far I only managed to make it work in this manner in case where all parameters have the same known type at the time of coding. After a number of attempts to tackle this problem with generic delegates I am starting to think this is not possible to achieve. Even when my code compiles, it does not work at runtime. Any takers? Thanks in advance for your help!

推荐答案

以下是使用泛型代理的示例:

Here's an example using generic delegates:

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始终相同,则可以删除所有 T s。

If ResultObjectType is always the same then you can remove all Ts.

这篇关于避免重复的代码在多个类似的方法(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆