在Windows 10 Universal Apps中使用CreateInstance [英] Using CreateInstance in Windows 10 Universal Apps

查看:146
本文介绍了在Windows 10 Universal Apps中使用CreateInstance的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码无法在Windows 10通用应用程序中编译,但可以在.Net控制台应用程序(均使用反射)中编译:

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);

通用Windows应用程序似乎不包含方法Assembly.GetExecutingAssembly(); Assembly对象似乎也不包含CreateInstance.

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在.Net中有16个重载,而在Win 10应用程序中只有3个重载.我指的是桌面扩展.

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

在Windows 10中仍然可以使用这种类型的构造吗?如果可以,怎么办?我想做的是从代表该类的字符串创建一个类的实例.

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.

推荐答案

CoreCLR/Windows 10等中的反射已将Type中的许多内容移到了 IntrospectionExtensions 来获取表示Type.例如:

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);

...具有程序集限定的类型名称,或当前正在执行的程序集或mscorlib中的类型名称.

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

这篇关于在Windows 10 Universal Apps中使用CreateInstance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆