注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 SWAT—Samba WEB管理..
 帮助

One Reflection application in .NET


2007-10-04 17:12:09
 标签:.NET   [推送到技术圈]

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://feishunji.blog.51cto.com/237830/45034
问题是这样的, 一个人想在发布自己项目的时候 不用发布它所引用的程序集.
我想 办法是这样的: 把程序集embed到自己的项目中再通过reflection机制来调用改程序集的方法啊 类啊 数据啊 什么的.
下面是一个例子.
-----------------ClassLibrary1.dll---------------------
namespace ClassLibrary1
{
    public class Class1
    {
        public void Show()
        {
            Console.WriteLine("Class1.Show is called...");
        }
    }
}
 
把上面的dll加到下面的项目中来并且把Build Action 设成 Embeded Resources
------------------Console app------------------
namespace ConsoleApplication1
{
 
    class Program
    {
        static void Main(string[] args)
        {
            Assembly dll;
            Assembly a = Assembly.GetExecutingAssembly();
            byte[] buffer=new byte[40480];//大小因程序集而异
            Stream stream = a.GetManifestResourceStream("ConsoleApplication1.ClassLibrary1.dll");
            int j = stream.Read(buffer, 0, buffer.Length);
            if (j > 0)
            {
                dll = Assembly.Load(buffer);
                Type[] t = dll.GetTypes();
                foreach (Type tt in t)
                {
                    if (tt.Name == "Class1")
                    {
                        object class1= Activator.CreateInstance(tt);
                        MethodInfo[] ms = tt.GetMethods();
                        foreach (MethodInfo m in ms)
                        {
                            if (m.Name == "Show")
                                m.Invoke(class1, null);
                        }
                    }
                }
            }
            Console.Read();
        }
    }
}
 
此方法因为要把整个assembly导入内存,所以 如果程序集太大显然就不行了...
 

本文出自 “费费笔记” 博客,请务必保留此出处http://feishunji.blog.51cto.com/237830/45034





    文章评论
 
 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: