简体   繁体   中英

How to load type from system dll using Activator.CreateInstance?

.Net 4.5.2 and 4.6.2, MSTest unit tests:

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. I've tried changing the referenced System assembly Copy Local property to true, but that seems to have no effect. 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. 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.

For example System.Uri is in System.dll , but System.Boolean is in mscorlib.dll .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM