实战 .Net 数据访问层 - 7

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值