加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – ReflectionOnlyGetType与GetType

发布时间:2020-12-15 05:36:56 所属栏目:百科 来源:网络整理
导读:我从api文档中了解到ReflectionOnlyGetType返回一个类型,就像GetType一样.区别在于使用ReflectionOnlyGetType,类型仅加载用于反射,而不是用于执行. 那为什么这个工作: Type t = Type.ReflectionOnlyGetType("System.Collections.Generic.List`1[[System.Str
我从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]],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中加载的?还是它完全不同?

解决方法

您正在加载mscorlib中的类型,该类型已加载以供运行时执行.您可以检查Assembly上的ReflectionOnly属性,以查看它是否已加载到ReflectionOnly上下文中.在你的样本中,
Type t = Type.ReflectionOnlyGetType("System.Collections.Generic.List`1[[System.String,false);
Console.WriteLine(t.Assembly.ReflectionOnly); // prints False.

似乎反映mscorlib有点受限制.从MSDN开始:

You cannot use the reflection-only context to load a version of
mscorlib.dll from a version of the .NET Framework other than the
version in the execution context.

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

它似乎与其他BCL程序集一起使用:

Console.WriteLine(Assembly.ReflectionOnlyLoad("System.Core,Version=4.0.0.0,PublicKeyToken=b77a5c561934e089").ReflectionOnly); // prints True

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读