[英]How to load type from system dll using Activator.CreateInstance?
.Net 4.5.2 and 4.6.2, MSTest unit tests: .Net 4.5.2和4.6.2,MSTest单元测试:
For test-case purposes I need to create 'system' objects by specifying the class name as a string in a data file. 出于测试用例的目的,我需要通过在数据文件中将类名指定为字符串来创建“系统”对象。 I only know the required type at runtime as a string type-name (possibly fully qualified). 我只在运行时将所需的类型知道为字符串类型名(可能是完全限定的)。
I've tried the fairly orthodox approach of 我已经尝试过
var assyName = "System"; //read from data file
var typeName = "System.Boolean"; //read from data file
var hndle = Activator.CreateInstance(assyName, typeName);
var obj = hndle.Unwrap();
var t = obj.GetType();
but whilst this works if I am loading my own type from my own assemblies, if I try it using a .Net assembly (as above) the Activator line throws a FileNotFound exception. 但是,如果我从自己的程序集中加载自己的类型,这是可行的,但是如果我使用.Net程序集(如上)进行尝试,则Activator行将引发FileNotFound异常。 I've tried changing the referenced System assembly Copy Local property to true, but that seems to have no effect. 我尝试将引用的系统程序集“复制本地”属性更改为true,但这似乎没有任何效果。 I've also tried specifying the full path to the System assembly, without luck. 我也尝试过指定系统程序集的完整路径,但是没有运气。
So the questions are: what am I doing wrong, and (if nothing wrong) how otherwise do I achieve my aim? 所以问题是:我在做什么错,以及(如果没有错的话)我如何才能实现目标?
Your data file is wrong. 您的数据文件错误。
The System.Boolean
type, just as many other types in the System
namespace reside in the mscorlib
assembly, not in the System
assembly which that data file claims. 与System
名称空间中的许多其他类型一样, System.Boolean
类型也驻留在mscorlib
程序集中,而不是在该数据文件声明的System
程序集中。 There is no relation between a namespace name and an assembly name. 命名空间名称和程序集名称之间没有关系。
You can see which assembly contains a type on that type's MSDN page. 您可以在该类型的MSDN页面上查看哪个程序集包含一个类型。
For example System.Uri
is in System.dll
, but System.Boolean
is in mscorlib.dll
. 例如, System.Uri
在System.dll
,而System.Boolean
在mscorlib.dll
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.