aov*_*ven 6 c# reflection types appdomain
我在使用以下代码时遇到了一些问题:
private class ClientPluginLoader : MarshalByRefObject
{
public bool IsPluginAssembly(string filename)
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomainReflectionOnlyAssemblyResolve);
Assembly asm = Assembly.ReflectionOnlyLoadFrom(filename);
Type[] types = asm.GetTypes();
foreach (Type type in types)
{
if (type.IsSubclassOf(typeof(ClientPlugin)))
{
return true;
}
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
代码是通过我通过自定义应用程序域的CreateInstanceFromAndUnwrap()创建的代理调用的.这意味着IsPluginAssembly()在我的自定义应用程序域的上下文中执行.
问题是对IsSubclassOf()的调用总是返回false,即使它应该返回true.所讨论的"类型"确实从ClientPlugin继承 - 毫无疑问.
ClientPlugin是在一个不同的私有程序集中定义的,我正在手动解析,如上面的代码片段所示.
我在线上放了一个断点if (type.IsSubclassOf(...))
并确认这个表达式是假的:
type.BaseType == typeof(ClientPlugin)
Run Code Online (Sandbox Code Playgroud)
另一方面,这个表达式是正确的:
type.BaseType.FullName == typeof(ClientPlugin).FullName
Run Code Online (Sandbox Code Playgroud)
这怎么可能?这是怎么回事?
更新:Kent Boogaart向我指出了正确的方向.我在网上搜索了一下,然后进入这篇博文.我似乎必须解决我的Load/LoadFrom/ReflectionOnlyLoadFrom冲突才能使其工作.
这是由于加载到不同的上下文.加载程序集的方式(Load/LoadFrom/ReflectionOnlyLoad)确定加载程序集的上下文.这个简单的例子也证明了这个问题:
using System;
using System.Reflection;
class Foo
{
public static void Main()
{
var type = typeof(Foo);
var reflectionLoadType = Assembly.ReflectionOnlyLoad("ConsoleApplication1").GetType("Foo");
Console.WriteLine(type == reflectionLoadType); //false
Console.WriteLine(type.Equals(reflectionLoadType)); //false
Console.WriteLine("DONE");
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参见此处
归档时间: |
|
查看次数: |
1501 次 |
最近记录: |