具有相似的方法代码但仅更改了调用者名称的情况下使用什么方法?

问题描述 投票:0回答:1

我正在设计一个只包装一些方法调用的类,这些方法是另一个类库的一部分。

这是我的班级样子:

public class MyClass
{
    IService Service; //Third Party Library.

    public MyClass()
    {
        // Initialization
    }

    public string MethodA()
    {
        Service.MethodA();
        return Service.GetResult();
    }

    public string MethodB()
    {
        Service.MethodB();
        return Service.GetResult();
    }

    public string MethodC()
    {
        Service.MethodC();
        return Service.GetResult();
    }

    public string MethodD()
    {
        Service.MethodD();
        return Service.GetResult();
    }
}

借助于反思,我在某种程度上重构了上面的代码,如下所示:

public class MyClass
{
    IService Service;

    public MyClass()
    {
        // Initialization
    }

    public string MethodA()
    {
       return GetResult(System.Reflection.MethodBase.GetCurrentMethod().Name);
    }

    public string MethodB()
    {
       return GetResult(System.Reflection.MethodBase.GetCurrentMethod().Name);
    }

    public string MethodC()
    {
       return GetResult(System.Reflection.MethodBase.GetCurrentMethod().Name);
    }

    public string MethodD()
    {
       return GetResult(System.Reflection.MethodBase.GetCurrentMethod().Name);
    }

    private string GetResult(string methodName)
    {
       Service.GetType().GetMethods().FirstOrDefault(x => x.Name == methodName).Invoke(Service, null);
       return Service.GetResult();
    }
}

我看到的一个缺点是,假设如果将来使用的库发布了新版本,并且方法名称有任何更改,则在使用反射时不会出现任何编译错误,但是在运行时,它将引发异常。

此方法是否有更好的替代解决方案?

c# .net .net-standard
1个回答
0
投票

我将使用您提供的两个选项中的任何一个,并添加单元测试以验证用于该特定版本的第三方库的版本是否仍然具有这些方法。实际上,您可以使用一些反射并深入研究那些单元测试,例如,检查方法签名是否相同等等。这些单元测试将保证您,如果第三方库中的方法已更改,则构建将失败。

一旦构建通过(及其所有的单元测试),就不必担心余下的生命周期。

((我本来会写评论而不是帖子,但是我没有足够的声誉)

© www.soinside.com 2019 - 2024. All rights reserved.