我继承了我需要扩展的代码并为其添加了一些功能。
我有一个基类,它存储具体对象列表“OrderA”:
private List<OrderA> _orders;
我想用通用的方法替换具体的对象实现。
现在我有:
/// <summary>
/// This is DataContract that received via a web service
/// </summary>
public class Order
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
public class OrderA : Order
{
public string Prop3 { get; set; }
}
// Base class
public class WorksheetBase
{
// Uses concrete OrderA object
private List<OrderA> _orders;
public void CreateWorksheet()
{
_orders = new List<OrderA>();
for (int i = 0; i < 5; i++)
{
var o = new OrderA();
o.Prop1 = string.Format("Value {0}", i);
_orders.Add(o);
}
}
public void SaveWorksheets()
{
if (_orders == null)
return;
foreach (var order in _orders)
{
Console.WriteLine(order.Prop1);
}
}
}
public class WorksheetA : WorksheetBase
{
OrderA[] _activeOrders;
public string Name { get; set; }
}
public class WorksheetB : WorksheetBase
{
OrderA[] _activeOrders;
public string Name { get; set; }
}
class Program
{
public static Dictionary<string, WorksheetBase> dic = new Dictionary<string, WorksheetBase>();
static void Main(string[] args)
{
WorksheetA fz = new WorksheetA();
fz.Name = "Work Sheet A";
fz.CreateWorksheet();
dic[fz.Name] = fz;
WorksheetB fwd = new WorksheetB();
fwd.Name = "Work Sheet B";
fwd.CreateWorksheet();
dic[fwd.Name] = fwd;
SaveWorksheets();
Console.ReadKey();
}
private static void SaveWorksheets()
{
foreach (var item in dic)
{
item.Value.SaveWorksheets();
}
}
}
现在我需要为(WorksheetC)添加一个新功能
public class OrderC : Order
{
public string Prop4 { get; set; }
}
public class WorksheetC : WorksheetBase
{
OrderC[] _activeOrders;
public string Name { get; set; }
}
我觉得实现泛型类型参数是正确的方法。
public class WorksheetBase<T>
{
private List<T> _orders;
public void CreateWorksheet()
{
_orders = new List<T>();
for (int i = 0; i < 5; i++)
{
....
}
}
public void SaveWorksheets()
{
if (_orders == null)
return;
foreach (var order in _orders)
{
Console.WriteLine(order.Prop1);
}
}
}
public class WorksheetA : WorksheetBase<OrderA>
{
OrderA[] _activeOrders;
public string Name { get; set; }
}
但是在实例化字典时我遇到错误:
public static Dictionary<string, WorksheetBase> dic = new Dictionary<string, WorksheetBase>();
也许我说这一切都错了,但这让我烦恼。有没有想过更好的方法来处理这个?我觉得我必须要错过一些简单的东西......