实战 .Net 数据访问层 - 7

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

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

Published At
Categories with Web编程
Tagged with
comments powered by Disqus