如何在Windows Phone應用程序中使用C#/ NET中的字符串名稱創建類的對象?如何從他的字符串名稱中創建一個類的對象?
例如,在PHP:
$a = 'MainClass';
$b = new $a();
我能做到這一點在C#/。NET的Windows Phone應用程序?
如何在Windows Phone應用程序中使用C#/ NET中的字符串名稱創建類的對象?如何從他的字符串名稱中創建一個類的對象?
例如,在PHP:
$a = 'MainClass';
$b = new $a();
我能做到這一點在C#/。NET的Windows Phone應用程序?
嘗試此(提供MainClass有默認構造):
// Depending on where you call it, it may require full class name: "MyNameSpace.MainClass"
var b = Activator.CreateInstance(Type.GetType("MainClass"));
非常感謝你 – iJoy
var obj = (MyType)Activator.CreateInstance("MyTypeAssembly", "MyType"))
您沒有'MyType' - 只有它的名字。否則,你可以簡單地執行'new MyType()' –
[此](http://msdn.microsoft.com/en-us/library/system.activator.createinstance。 aspx)是你在找什麼 –
你google? –
This [post](http://stackoverflow.com/questions/223952/c-sharp-create-an-instance-of-a-class-from-a-string)可能已經回答了你的問題。 – Dong