实战 .Net 数据访问层 - 7-.NET教程,数据库应用
来源:作者: 发布时间:2007-12-26 02:11:00


最后,和大家讨论一个由于引入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)!
|
还没有关于此文章的相关评论!