[英]In C#, if the (string) class name is known, how to instantiate an object from that (string) class?
在C#中,如何針對類實例化對象; 但是類名在字符串變量中?**
String stringNameOfClass = "SomeClass";
{stringNameOfClass} theObject = new {stringNameOfClass}();
在js中,我認為我們可以使用eval()
var stringNameOfClass = "SomeClass";
eval('var theInstance = new ' + stringNameOfClass + '()');
theInstance.accessMethod();
[編輯]給定:類名未知,但方法已知
我可以在給定的文件夾中獲取所有類的名稱。 現在,我想通過它們的名稱空間相應地實例化它們。 雖然,我知道我感興趣的方法。
arrayOfString = getAllClassesByNamespace('TheNamespace','/path');
// now call testMe() per instance
foreach (string str in arrayOfString )
{
{str} arrayOfString[str] = new {str};
str.testMe();
//in js
eval('var obj_' + arrayOfString[str] + ' = new ' + arrayOfString[str] + '()');
//if first class found is TheClass.. this is what I want to do
TheClass obj_TheClass = new TheClass();
obj_TheClass.testMe();
}
我認為您正在尋找Activator.CreateInstance方法,它將使用許多參數,但是有一個參數將使用TypeName和Namespace允許您從其名稱創建新類的實例。
https://msdn.microsoft.com/zh-CN/library/d133hta4(v=vs.110).aspx
這是我發現的如何從字符串實例化類的最直接的解決方案: https : //msdn.microsoft.com/zh-cn/library/a89hcwhh.aspx
public class TestMethodInfo
{
public static void Main()
{
// Get the constructor and create an instance of MagicClass
String stringedClass = "MagicClass";
String stringedClassMethod = "theMethod";
Type magicType = Type.GetType(stringedClass);
ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
object magicClassObject = magicConstructor.Invoke(new object[]{});
// Get the ItsMagic method and invoke with a parameter value of 100
MethodInfo magicMethod = magicType.GetMethod(stringedClassMethod);
object magicValue = magicMethod.Invoke(magicClassObject, new object[]{100});
Console.WriteLine("MethodInfo.Invoke() Example\n");
Console.WriteLine("MagicClass.theMethod() returned: {0}", magicValue);
}
}
干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.