1

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

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

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

Activator.CreateInstance 在 .Net 中有 16 个重载,而在 Win 10 应用程序中只有 3 个。我正在引用桌面扩展。

这种类型的构造在 Windows 10 中是否仍然可行,如果可以,如何实现?我要做的是从代表该类的字符串创建一个类的实例。

4

1 回答 1

2

CoreCLR/Windows 10 等中的反射已经将很多过去的内容转移TypeTypeInfo. 您可以使用IntrospectionExtensionsTypeInfo获取Type. 例如:

using System.Reflection;
...

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

希望所有这些都可供您使用(根据我的经验,文档可能有点令人困惑)。或者你可以只使用:

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

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

于 2015-11-03T18:35:07.693 回答