實戰 .Net 數據訪問層 - 7

 <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

最後,和大家討論一個由於引入Def而產生的技術問題。

老規矩,還是先請各位看一段代碼:

 

代碼6Interface Inheritance下的Def多態問題

public abstract class DefBase : IList, IDictionary

{

    // 既是Interface方法,又被聲明爲virtual

    public virtual IEnumerator GetEnumerator()

    {

       if (_al != null)

           return _al.GetEnumerator();

       else if (_ht != null)

           return _ht.GetEnumerator();

       else

       {

           // 拋出基類無法處理異常

           throw new Exception(

"Do not handle interface method in DefBase class !");

       }

    }

}

 

public class MyDef: DefBase, IList, IEnumerable

{

    // 既是Interface方法,又被聲明爲override

    public override IEnumerator GetEnumerator()

    {

       try

       {

           // 先調用DefBaseInterface方法,

           //   如果基類無法處理,截獲其拋出的異常

           return base.GetEnumerator();

       }

       catch

       {

           if (this._ostOrm != null)

              return GetList().GetEnumerator();

           else if (this._xmlNode != null)

              return _xmlNode.GetEnumerator();

           else if (this._xmlDoc != null)

              return _xmlDoc.GetEnumerator();

           else

              throw new Exception(

"Do not handle interface method in MyDef class !");

           }

       }

    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

不知道註釋部分是否已表述清楚:當繼承自Interface後,由於還是存在Base ClassDefBase)這樣一個事實,MyDef如果要擴展這個Interface實現,就不得不進行virtual / override聲明!

同時,由於MyDef實例也存在“僅使用DefBase Interface Implementation足矣”這種情況(例如:Entity Type就是ArrayListHashtable),促使我們不得不採用一些非常手段進行調理!

 

這裏,作者採用了異常處理的方法進行判斷(有點取巧的味道),一旦基類DefBase無法處理,就直接throw exception(如果考慮全面點,還需事先定義exception type以進行過濾處理),這樣層層往上推進,如果最後進行catch的類依然無法處理,那就真的是系統異常了!

還有一種做法稍微複雜點:在DefBase中可以返回null並在MyDef中進行判斷,不過,對於不返回任何值或返回值爲ValueTypeInterface Method,就必須另闢蹊徑了(例如:單獨定義一個Null Type Class進行處理,類似.NET Framework中的System.DBNull)!

 

下一段:http://www.csdn.net/develop/Read_Article.asp?id=27550

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章