【发布时间】:2017-04-07 10:49:39
【问题描述】:
我正在制作一个 C# 应用程序。该应用程序有两个类和多个方法。在编写代码时,我偶然发现了一个问题。我在两个类中使用相同的两个变量(XList 和 YList)和一种方法。并且可能我需要更多带有此代码的类。所以我创造了一个重复问题。以下是我的代码的简单版本:
public class A {
private testEntities db = new testEntities();
public List<int> XList = new List<int>();
public List<int> YList = new List<int>();
public void GetAllInfo()
{
// Get the data from a database and add to a list
XList = db.Table1.ToList();
YList = db.Table2.ToList();
}
public void DoStuff()
{
// Do Stuff with XList and YList
}
}
public class B {
private testEntities db = new testEntities();
public List<int> XList = new List<int>();
public List<int> YList = new List<int>();
public void GetAllInfo()
{
// Get the data from a database and add to a list (the same as in class A)
XList = db.Table1.ToList();
YList = db.Table2.ToList();
}
public void DoDifferentStuff()
{
// Do ddifferent stuff with XList and YList then in class A
}
}
我的问题是解决这个重复问题的最佳方法是什么?
经过一些研究,我发现我可能可以通过继承或组合来解决这个问题。我还读到人们选择组合而不是继承。所以我写了以下代码来解决重复:
public class DataPreparation
{
private testEntities db = new testEntities();
public List<int> XList = new List<int>();
public List<int> YList = new List<int>();
public void GetAllInfo()
{
// Get the data from a database and add to a list
XList = db.Table1.ToList();
YList = db.Table2.ToList();
}
// Implement other methods
}
public class A
{
public void MethodName()
{
DataPreparation dataPreparation = new DataPreparation();
dataPreparation.GetAllInfo();
UseDataX(dataPreparation.XList);
UseDataY(dataPreparation.YList);
// Implementation UseDataX() and UseDataY()
}
}
public class B
{
public void MethodName()
{
DataPreparation dataPreparation = new DataPreparation();
dataPreparation.GetAllInfo();
VisualizeDataX(dataPreparation.XList);
VisualizeDataY(dataPreparation.YList);
// Implementation VisualizeDataX() and VisualizeDataY()
}
}
如您所见,我创建了一个类来处理从数据库中获取数据。并且A类和B类使用DataPreparation类。 但这是解决重复问题的最佳方法吗?还是应该使用继承或其他方式?
【问题讨论】:
-
起点:您打算如何测试您的方法?
标签: c# code-duplication