一个使用.net反射(Reflection)的例子

 

ProfileCommon是继承自ProfileBase的一个类,可以使用它很方便的访问用户的Profile

在业务层里用到了ProfileCommon类,大致如下:

ProfileCommon pro=new ProfileCommon();

pro=pro.GetProfile(username);

return pro.PhoneNum;

以前业务层代码都放到app_code下,所以一切正常。但是现在想把业务层放到一个库文件里,问题就出来了,大家知道ProfileCommon类是asp.net自动生成的,根本没法在当前的asp.net website之外使用。

 

解决方案

 

当我们调用GetProfile(username)时,它只是返回一个由ProfileBase.Creat(username)生成的对象,这个方法会把存在数据库中的Profile信息deserialize成一个ProfileBase对象。如果我们在运行时去检测它的类型,就会发现它实际上也是一个profileCommon对象,利用.net的反射特征,有了以下代码。

object  pro=ProfileBase.Create(Poster);

string phone = pro.GetType().InvokeMember("Phone", BindingFlags.Default|BindingFlags.GetProperty, null, pro, null);

return phone;

 

总结

其实是很简单的一个例子而已,不过以前都没怎么意识到动态类型的好处,突然发现原来它那么强,呵呵。

posted @ 2007-06-22 15:05  心利  阅读(864)  评论(3)    收藏  举报
SharePoint Add-ons