2013-07-16 131 views
-2

如何在Windows Phone應用程序中使用C#/ NET中的字符串名稱創建類的對象?如何從他的字符串名稱中創建一個類的對象?

例如,在PHP:

$a = 'MainClass'; 
$b = new $a(); 

我能做到這一點在C#/。NET的Windows Phone應用程序?

+0

[此](http://msdn.microsoft.com/en-us/library/system.activator.createinstance。 aspx)是你在找什麼 –

+0

你google? –

+0

This [post](http://stackoverflow.com/questions/223952/c-sharp-create-an-instance-of-a-class-from-a-string)可能已經回答了你的問題。 – Dong

回答

2

嘗試此(提供MainClass有默認構造):

// Depending on where you call it, it may require full class name: "MyNameSpace.MainClass" 
    var b = Activator.CreateInstance(Type.GetType("MainClass")); 
+0

非常感謝你 – iJoy

0
var obj = (MyType)Activator.CreateInstance("MyTypeAssembly", "MyType")) 
+2

您沒有'MyType' - 只有它的名字。否則,你可以簡單地執行'new MyType()' –

相關問題