我创建了一个静态方法,其目的是加载DLL,并使用反射,返回其中包含的类的实例。
为了让你有正确的心态,一些事实:
ListLabel
中的baseClass
公共成员)而间接加载的第三方DLL发生异常。以下是发生异常的方法:
namespace MyNamespace
{
public abstract class baseClass
{
public ListLabel LL = new ListLabel(); //this is where the exception actually originates
public baseClass()
{
LL.DrawPage += new DrawPageHandler(LL_DrawPage);
LL.EnableCallbacks = true;
LL.AddVarsToFields = true;
LL.DelayTableHeader = true;
LL.IncrementalPreview = true;
}
public static baseClass GetClassInstance(String DLLName)
{
try
{
if (!String.IsNullOrEmpty(DLLName))
{
String fileName = DLLName.EndsWith(".dll") ? DLLName : DLLName + ".dll";
Assembly theDLL = Assembly.LoadFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName));
foreach (Type t in theDLL.GetTypes())
{
if (typeof(baseClass).IsAssignableFrom(t))
return (baseClass)Activator.CreateInstance(t); //this line instantiates the baseClass instance, and causes the new LL object to be created, firing the exception
}
}
}
catch (Exception ex)
{
if (ex is ReflectionTypeLoadException)
{
Exception[] exa = ((ReflectionTypeLoadException)ex).LoaderExceptions;
for (Int32 i = 0; i < exa.Length; i++)
ErrorHandler.WriteError(String.Format("ReflectionTypeLoadException occurred while loading DLL '{0}' (ex #{1}):\n {2}", DLLName, i, exa[i].ToString()));
}
else
{
ErrorHandler.WriteError(String.Format("Error loading DLL: {0}", DLLName));
}
}
return null;
}
}
}
请注意,baseClass
是静态方法的提供者,它是abstract
,它是GetClassInstance()
返回的类型。
我得到的是偶尔的异常集,其核心是AccessViolationException
。我收到的堆栈跟踪如下:
at combit.ListLabel18.NativeMethods.LlSetDebug32(Int32 nOnOff)
在combit.ListLabel18.LlCore.LlSetDebug(LlDebug onOff)at at combit.ListLabel18.ListLabel.set_Debug(LlDebug value)at combit.ListLabel18.ListLabel.Init(LlLanguage语言,CultureInfo culture,Boolean enableCallbacks,String debugLogFilePath)at AllMax.baseReport..ctor()的combit.ListLabel18.ListLabel..ctor()
at AllMaxReport.rpt3320DMR..ctor()at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly,Boolean skipVisibilityChecks,Boolean fillCache)
这无论如何都不一致,这也是我担心这是我的错的主要原因。这可能与以下组合有关:
GetClassInstance()
时会发生。)static
方法。reflection
放入static
方法。static
方法的同一个类的实例。