[英]Using CreateInstance in Windows 10 Universal Apps
以下代碼不在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中這種類型的構造仍然可行嗎? 我想做的是從代表該類的字符串創建一個類的實例。
反思CoreCLR / 10的Windows等移動相當多的曾經被認為是在Type
為TypeInfo
。 您可以使用IntrospectionExtensions
來獲取Type
的TypeInfo
。 因此,例如:
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中的類型名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.