日期:2012-04-05  浏览次数:20557 次

最后,和大家讨论一个由于引入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)!