Using CreateInstance in Windows 10 Universal Apps

2019-08-08 10:21发布

问题:

The following code doesn't compile in a Windows 10 Universal App, but does in a .Net console app (both using Reflection):

string objType = "MyObjType";
var a = Assembly.GetExecutingAssembly();
var newObj = a.CreateInstance(objType);

It would appear that universal windows apps don't contain the method Assembly.GetExecutingAssembly(); nor do the Assembly objects seem to contain CreateInstance.

Activator.CreateInstance has 16 overloads in .Net and only 3 in A Win 10 app. I'm referencing the desktop extensions.

Is this type of construct still possible in Windows 10 and, if so, how? What I'm trying to do is to create an instance of a class from a string representing that class.

回答1:

Reflection in CoreCLR / Windows 10 etc has moved quite a lot of what used to be in Type into TypeInfo. You can use IntrospectionExtensions to get the TypeInfo for a Type. So for example:

using System.Reflection;
...

var asm = typeof(Foo).GetTypeInfo().Assembly;
var type = asm.GetType(typeName);
var instance = Activator.CreateInstance(type);

Hopefully all of that is available to you (the docs can be a little confusing, in my experience). Or you could just use:

var type = Type.GetType(typeName);
var instance = Activator.CreateInstance(type);

... with either an assembly-qualified type name, or the name of a type in the currently-executing assembly or mscorlib.