2011-03-02 20 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基於這種方法,從中可以得出未來實現其提供了可以前後核心方法後調用虛函數的通用基類。

相關問題