c# – ReflectionOnlyGetType与GetType

前端之家收集整理的这篇文章主要介绍了c# – ReflectionOnlyGetType与GetType前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我从api文档中了解到ReflectionOnlyGetType返回一个类型,就像GetType一样.区别在于使用ReflectionOnlyGetType,类型仅加载用于反射,而不是用于执行.

那为什么这个工作:

@H_301_4@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上下文中.在你的样本中,@H_301_4@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程序集一起使用:

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

猜你在找的C#相关文章