本文整理汇总了C#中System.AppDomain.TypeResolve事件的典型用法代码示例。如果您正苦于以下问题:C# AppDomain.TypeResolve事件的具体用法?C# AppDomain.TypeResolve怎么用?C# AppDomain.TypeResolve使用的例子?那么, 这里精选的事件代码示例或许可以为您提供帮助。您也可以进一步了解该事件所在类System.AppDomain
的用法示例。
在下文中一共展示了AppDomain.TypeResolve事件的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using System.Reflection;
using System.Reflection.Emit;
class Test
{
// For this code example, the following information needs to be
// available to both Main and the HandleTypeResolve event
// handler:
private static AssemblyBuilder ab;
private static string moduleName;
public static void Main()
{
AppDomain currDom = AppDomain.CurrentDomain;
// Create a dynamic assembly with one module, to be saved to
// disk (AssemblyBuilderAccess.Save).
//
AssemblyName aName = new AssemblyName();
aName.Name = "Transient";
moduleName = aName.Name + ".dll";
ab = currDom.DefineDynamicAssembly(aName,
AssemblyBuilderAccess.Save);
ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, moduleName);
// The dynamic assembly has just one dummy type, to demonstrate
// type resolution.
TypeBuilder tb = mb.DefineType("Example");
tb.CreateType();
// First, try to load the type without saving the dynamic
// assembly and without hooking up the TypeResolve event. The
// type cannot be loaded.
try
{
Type temp = Type.GetType("Example", true);
Console.WriteLine("Loaded type {0}.", temp);
}
catch (TypeLoadException)
{
Console.WriteLine("Loader could not resolve the type.");
}
// Hook up the TypeResolve event.
//
currDom.TypeResolve +=
new ResolveEventHandler(HandleTypeResolve);
// Now try to load the type again. The TypeResolve event is
// raised, the dynamic assembly is saved, and the dummy type is
// loaded successfully. Display it to the console, and create
// an instance.
Type t = Type.GetType("Example", true);
Console.WriteLine("Loaded type \"{0}\".", t);
Object o = Activator.CreateInstance(t);
}
static Assembly HandleTypeResolve(object sender, ResolveEventArgs args)
{
Console.WriteLine("TypeResolve event handler.");
// Save the dynamic assembly, and then load it using its
// display name. Return the loaded assembly.
//
ab.Save(moduleName);
return Assembly.Load(ab.FullName);
}
}
输出:
Loader could not resolve the type. TypeResolve event handler. Loaded type "Example".