我从接口文档中了解到,与GetType非常类似,ReflectionOnlyGetType返回一个类型。不同之处在于,使用ReflectionOnlyGetType时,加载该类型只是为了反射,而不是为了执行。
那么为什么这样做是可行的:
Type t = Type.ReflectionOnlyGetType("System.Collections.Generic.List`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", false, false);
ConstructorInfo[] cis = t.GetConstructors();
foreach (ConstructorInfo ci in cis)
{
if (ci.GetParameters().Length == 0)
{
// ! no arg constructor found! let's call it!
Object o = ci.Invoke(new Object[]{});
Console.WriteLine("But wait, it was supposed to be reflection only??");
Console.WriteLine(o.GetType().Name);
List<String> lli = (List<String>)o;
lli.Add("but how can this be?");
Console.WriteLine(lli.Count);
Console.WriteLine("I am doing a lot more than reflection here!");
}
}我的问题是:我似乎能够做更多的事情,而不是反思这类成员。当他们说类型被加载“只是为了反射,而不是为了执行”时,我是否误解了“执行”?或者,如果一个类型已经被“加载”了,那么ReflectionOnlyGetType是否返回了一个不同的(非反射的)类型?或者它是完全不同的东西?
发布于 2012-11-21 16:32:24
您正在从mscorlib加载一个类型,该类型已被加载以供运行时执行。您可以检查程序集的ReflectionOnly属性,以查看它是否加载到ReflectionOnly上下文中。在你的样本中,
Type t = Type.ReflectionOnlyGetType("System.Collections.Generic.List`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", false, false);
Console.WriteLine(t.Assembly.ReflectionOnly); // prints False.似乎在mscorlib上的反射受到了一定的限制。来自MSDN
不能使用仅反射上下文从除执行上下文中的版本之外的其他版本的.NET框架加载mscorlib.dll版本。
我猜这会扩展到将当前执行上下文中的一个加载到仅反射上下文中。
它似乎可以与其他BCL程序集一起工作:
Console.WriteLine(Assembly.ReflectionOnlyLoad("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").ReflectionOnly); // prints Truehttps://stackoverflow.com/questions/13488818
复制相似问题