Using CreateInstance in Windows 10 Universal Apps

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 14:08:57

问题


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.



来源:https://stackoverflow.com/questions/33494138/using-createinstance-in-windows-10-universal-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!