我正在制作一个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类。 但这是解决重复的最佳方法吗?或者我应该使用继承还是不同的东西?
开始点:您计划如何测试您的方法? – tym32167