享受代码,享受人生

SOA is an integration solution. SOA is message oriented first.
The Key character of SOA is loosely coupled. SOA is enriched
by creating composite apps.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Generics to Eliminate Casting ?

Posted on 2005-08-01 15:46  idior  阅读(2094)  评论(6编辑  收藏  举报

这个问题是很久以前在一个老外的blog上看到的,当时没有很在意,最近看了CAB(Composition UI Application Block)的源码后, 又想到它.利用泛型来确保参数的类型安全, 我想这是泛型的重要意义之一.但是利用泛型完成返回值类型(Return Value Typr)的自动转化(Casting), 你想过没有?

以GetService方法为例, 在没有泛型的时候是这样的.

public interface IServiceProvider
{  
   Object GetService(Type serviceType);
}


在使用的时候,我们需要显式(explicit)将获得的Service对象转化(Casting)为相应的类型.

public void Foo()

 IMyService service 
= (IMyService) provider.GetService(typeof(IMyService));
}

但是在有了泛型的支持后,我们可以这样做.

 

public interface IServiceProvider

   T GetService
<T>();
}


public void Foo()
{  
   IMyService service 
= provider.GetService<IMyService>();
}

没有了Casting, 没有了参数, 看上去简洁多了. Is it a perfact solution? No!

要知道泛型的重要意义在于提供类型安全(Type safe). 在目前的这个方法中, 并没有涉及到类型安全的问题. 而且在实际的实现中,该方法仅仅做了一个Casting的包装.并且使用泛型的方法效率要比不使用低的多.

public T GetService<T>()
{  
    
return (T) GetService(typeof(T));
}

so. what's your opinion?  CAB(Composition UI Application Block)使用了这个方法.

BTW: CAB is a very cool MVC Framework in smartclient, you will soon be familiar with it.
It's Highly Recommanded you check it out. I hope i can give some introduction about it in future.