實戰 .Net 數據訪問層 - 7
2024-07-10 13:03:23
供稿:網友
最后,和大家討論一個由于引入def而產生的技術問題。
老規矩,還是先請各位看一段代碼:
代碼6:interface 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
{
// 先調用defbase的interface方法,
// 如果基類無法處理,截獲其拋出的異常
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 class(defbase)這樣一個事實,mydef如果要擴展這個interface實現,就不得不進行virtual / override聲明!
同時,由于mydef實例也存在“僅使用defbase interface implementation足矣”這種情況(例如:entity type就是arraylist或hashtable),促使我們不得不采用一些非常手段進行調理!
這里,作者采用了異常處理的方法進行判斷(有點取巧的味道),一旦基類defbase無法處理,就直接throw exception(如果考慮全面點,還需事先定義exception type以進行過濾處理),這樣層層往上推進,如果最后進行catch的類依然無法處理,那就真的是系統異常了!
還有一種做法稍微復雜點:在defbase中可以返回null并在mydef中進行判斷,不過,對于不返回任何值或返回值為valuetype的interface method,就必須另辟蹊徑了(例如:單獨定義一個null type class進行處理,類似.net framework中的system.dbnull)!