Avoiding repetitive code in multiple similar methods (C#)

前端 未结 2 1208
清歌不尽
清歌不尽 2021-01-17 03:45

Greetings everyone!

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:

相关标签:
2条回答
  • 2021-01-17 03:54

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

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

    0 讨论(0)
  • 2021-01-17 04:14

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

    You should concentrate to make this parts as isolated as possible.

    Another approach is code generation.

    0 讨论(0)
提交回复
热议问题