ReflectionOnlyGetType与GetType

时间:2012-11-21 08:06:47

标签: c# .net

我从api文档中了解到ReflectionOnlyGetType返回一个类型,就像GetType一样。不同之处在于,使用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返回一个不同的(非反射)类型,如果类型已经“加载”并且这里是由于在mscorlib中加载的?或者它完全不同?

1 个答案:

答案 0 :(得分:3)

您正在加载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

  

您不能使用仅反射上下文来加载版本的   mscorlib.dll来自.NET Framework以外的版本   执行上下文中的版本。

我猜这扩展到将当前执行上下文中的一个加载到仅反射上下文中。

它似乎适用于其他BCL程序集:

Console.WriteLine(Assembly.ReflectionOnlyLoad("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").ReflectionOnly); // prints True
相关问题