Assembly 类

下面的代码示例演示如何获取当前执行的程序集,如何创建该程序集中包含的某个类型的实例以及如何用后期绑定调用该类型的方法之一。 为此,该代码示例定义了一个名为Example 的类,该类具有一个名为 SampleMethod 的方法。 该类的构造函数接受整数,用于计算方法的返回值。

该代码示例还演示如何使用 GetName 方法来获取可用于分析程序集的全名的 AssemblyName 对象。 该示例显示程序集的版本号、CodeBase 属性和 EntryPoint 属性。

 

using System;
using System.Reflection;
using System.Security.Permissions;

namespace ConsoleApplication1
{

[assembly: AssemblyVersionAttribute("1.0.2000.0")]

public class Example
{
private int factor;
public Example(int f)
{
factor = f;
}

public int SampleMethod(int x)
{
Console.WriteLine("\nExample.SampleMethod({0}) executes.", x);
return x * factor;
}

public static void Main()
{
Assembly assem = Assembly.GetExecutingAssembly();

Console.WriteLine("Assembly Full Name:");
Console.WriteLine(assem.FullName);

// The AssemblyName type can be used to parse the full name.
AssemblyName assemName = assem.GetName();
Console.WriteLine("\nName: {0}", assemName.Name);
Console.WriteLine("Version: {0}.{1}",
assemName.Version.Major, assemName.Version.Minor);

Console.WriteLine("\nAssembly CodeBase:");
Console.WriteLine(assem.CodeBase);

// Create an object from the assembly, passing in the correct number
// and type of arguments for the constructor.
// 加上命名空间
Object o = assem.CreateInstance("ConsoleApplication1.Example", false,
BindingFlags.ExactBinding,
null, new Object[] { 2 }, null, null);

// Make a late-bound call to an instance method of the object.
MethodInfo m = assem.GetType(" ConsoleApplication1.Example").GetMethod("SampleMethod"); //加上命名空间

Object ret = m.Invoke(o, new Object[] { 42 });
Console.WriteLine("SampleMethod returned {0}.", ret);

Console.WriteLine("\nAssembly entry point:");
Console.WriteLine(assem.EntryPoint);
Console.ReadKey();
}
}

}

 

posted on 2014-01-10 18:18  Precise  阅读(192)  评论(0编辑  收藏  举报

导航