2011-03-02 18 views
0

我有一个自定义的类,基本上是一个SortedList与一些额外的属性和方法。当添加新的键/值对时(即调用.Add方法时),我希望做一些额外的处理。我可以隐藏.Add方法或使用其他方法名称(例如:.AddPair),然后在该方法中调用base.Add。首选方法?为什么?隐藏SortedList的.Add方法vs使用另一个方法名称与base.Add

隐藏。新增方法:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text;  
namespace Inheritence_Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      DYseries d = new DYseries() { FieldName = "test" }; 
      d.Add(new DateTime(2010, 12, 1), 2345); 
      d.Add(new DateTime(2010, 12, 5), 2340); 
      d.Add(new DateTime(2010, 12, 2), 2343); 
      Console.WriteLine("fieldName {0} \n count {1} \n max {2} \n min {3}", d.FieldName, d.Count(), d.Keys.Max(), d.Keys.Min()); 
     } 
    } 
    class DYseries : SortedList<DateTime, double> 
    { 
     public string FieldName { get; set; } 
     new public void Add(DateTime date, double value) 
     { 
      base.Add(date,value); 
      // additional processing here 
      Console.WriteLine("Added date {0}.\n Max date: {1}",date, this.Keys.Max()); 
     } 

    } 
} 

使用另一种方法名称:

class Program 
    { 
     static void Main(string[] args) 
     { 
      DYseries d = new DYseries() { FieldName = "test" }; 
      d.AddPair(new DateTime(2010, 12, 1), 2345); 
      d.AddPair(new DateTime(2010, 12, 5), 2340); 
      d.AddPair(new DateTime(2010, 12, 2), 2343); 
      d.AddPair(new DateTime(2010, 12, 9), 2348); 
      Console.WriteLine("fieldName {0} \n count {1} \n max {2} \n min {3}", d.FieldName, d.Count(), d.Keys.Max(), d.Keys.Min()); 
     } 
    } 
    class DYseries : SortedList<DateTime, double> 
    { 
     public string FieldName { get; set; } 
     public void AddPair(DateTime date, double value) 
     { 
      base.Add(date,value); 
      // additional processing here 
      Console.WriteLine("Added date {0}.\n Max date: {1}",date, this.Keys.Max()); 
     } 

    } 

是否有一个优选的方法?一种方法(隐藏?)可能会导致问题吗?

回答

2

使用第二种方法。第一个打破了良好的面向对象设计,你不会确定你的方法是否会被调用或基类。考虑这个使用你的类:

SortedList<DateTime, double> myList = new DYseries(); 
myList.Add(date, value); // This will call the base, not your implementation! 

我从来没有碰到过一个正当的理由来使用new;总有其他方法可以在不破坏良好的面向对象设计的前提下实现你想要的东西。

2

您是否考虑过在这里使用聚合而不是继承?

就像SortedList一样,您的DYSeries类实现了IDictionary<>, ICollection<>, IEnumerable<>, IDictionary, ICollection, IEnumerable。然后有一个SortedList的私有成员实例,您将委托所有方法和属性实现,并添加额外的处理。这将确保不存在调用者无意调用本地SortedList.Add等的风险。

你甚至可以借此进一步与creaet基于这种方法,从中可以得出未来实现其提供了可以前后核心方法后调用虚函数的通用基类。

相关问题