2015-11-03 87 views
1

下面的代码不会在Windows 10通用的应用程序编译,但确实在.NET控制台应用程序(包括使用Reflection):在Windows 10的通用应用程序使用的CreateInstance

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中仍然可能,如果是这样的话,怎么样?我想要做的是从代表该类的字符串中创建一个类的实例。

+0

听起来像你想要的类型,例如用'Assembly.GetType(...)',然后调用'Activator.CreateInstance(Type)'。输入哪个组件? –

+0

该类型在当前程序集中(为什么我要调用GetExecutingAssembly),因此如果能够执行程序集,我当然可以这么做。 –

+1

那么你不能使用'typeof(Foo).Assembly',其中'Foo'是你写代码的类型吗? –

回答

2

在CoreCLR/Windows 10等中的反思已经将Type以前的很多东西转移到TypeInfo中。您可以使用IntrospectionExtensions获取TypeInfo,获得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程序类型的名称。

相关问题