Assembly.LoadFrom()和Assembly.LoadFile()的区别

                System.Reflection.Assembly类有两个静态方法:Assembly.Load(string assemblyname)和Assembly.LoadFrom(string filename) 。通常用这两个方法把程序集加载到应用程序域中。 如果你希望加载的程序集超出了CLR的预定探查范围,你可以用 Assembly.LoadFrom直接从一个文件位置加载程序集。Assembly.LoadFrom()和Assembly.LoadFile(),两者的主要区别有两点:

               一:Assembly.LoadFile()只载入指定的dll文件,而不会自动加载相关的dll文件。如果下文例子使用Assembly.LoadFile()加载SayHello.dll,那么程序就只会加载SayHello.dll而不会去加载SayHello.dll引用的BaseClass.dll文件。

               二:用Assembly.LoadFrom()载入一个Assembly时,会先检查前面是否已经载入过相同名字的Assembly;而Assembly.LoadFile()则不会做类似的检查。

    

using System;
using System.Collections.Generic;
using System.Text;

namespace BaseDLL
{
    public class BaseClass
    {
        public static void SetTitle()
        {
            Console.WriteLine("BaseClass中的方法");
        }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.Text;

namespace SayHello
{
    public class HelloClass
    {
        public string SayHello(int helloTimes, string name)
        {
            BaseDLL.BaseClass.SetTitle();
            string reslut = string.Empty;
            for (int i = 0; i < helloTimes; i++)
            {
                reslut += "Hello," + name + "\n"; 
            }
            return reslut;
        }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;

namespace Reflection
{
    class Program
    {
        static void Main(string[] args)
        {
        handle01:
            Console.WriteLine("请输入加载的DLL的位置:");
            string filePath = Console.ReadLine();
            if (File.Exists(filePath))
            {
                System.Reflection.Assembly ass = Assembly.LoadFrom(filePath);
                Type[] collection = ass.GetTypes();
                foreach (var item in collection)
                {
                    string className = item.FullName.ToString();
                    Console.WriteLine(className);
                }
            }
            else
            {
                Console.WriteLine("文件不存在,请重新输入文档地址");
                goto handle01;
            }
            Console.ReadKey();
        }
    }
}
View Code

 

posted @ 2014-09-26 14:04  徘徊在路上  阅读(3287)  评论(0编辑  收藏  举报