下面的以下代码是否足够好,还是应该使用类似接口或抽象类的东西?

我有一些通用的代码,但是没有看到抽象类或接口的原因。

另外,如果不探索或悬停在基础之上,就无法告诉serviceClient来自BaseTask。每个Task1和Task2中是否都有东西可以表明这一点?

public class BaseTask
{
    private string configValue1 = "abc";
    private string configValue2 = "def";

    public ServiceClient serviceClient = new ServiceClient(configValue1,configValue2);
}

public class Task1 : BaseTask
{
    public void RunTask()
    {
        serviceClient.RunTask1();
    }

}

public class Task2 : BaseTask
{
    public void RunTask()
    {
        serviceClient.RunTask2();
    }

}

public class BaseTask
{
    private readonly string configValue1 = "abc";
    private readonly string configValue2 = "def";

    private readonly ServiceClient serviceClient = new ServiceClient(configValue1,configValue2);

    public ServiceClient ServiceClient { get{ return serviceClient;} }
}

public class Task1 : BaseTask
{
    public void RunTask()
    {
        ServiceClient.RunTask1();
    }

}

public class Task2 : BaseTask
{
    public void RunTask()
    {
        ServiceClient.RunTask2();
    }

}

最佳答案

从结构上讲,我只是将serviceClient设置为只读属性。从风格上讲,我将遵循.NET的正确大小写约定:

private ServiceClient serviceClient = new ServiceClient(configValue1,configValue2);

public ServiceClient ServiceClient
{
    get { return serviceClient; }
}


RunTask虚拟化也可能是有道理的,因为您显示的实现是相同的(并且如果需要,它允许您在其他实现中覆盖它):

public virtual void RunTask()
{
    serviceClient.RunTask1();
}

09-28 04:27