因为我没有输入名称空间+类名(我只输入了类名(,所以我收到了一个异常错误。
我写了很多课,我收到了一个字符串。我想直接声明并初始化String的值为的类。我不想浏览每一个编写的类来查看哪个是
class Car
{
public void startCar()
{
Console.WriteLine("Car started");
}
}
class Main
{
private void treeView1_Click(object sender, EventArgs e)
{
String s="Car"
// I said Car obj because that's the value of the string
Car obj = new Car();
// or like this
value.string obj = new value.string();
obj.startCar();
}
}
您必须使用反射,但您需要一个完全限定的类名,因此如果您只有类名,则必须决定一个默认名称空间:
Type objType = Type.GetType("TheNamespace." + className);
object obj = Activator.CreateInstance(objType);
MethodInfo myMethod = objType.GetMethod(methodName);
myMethod.Invoke(obj, // The object on which to invoke the method
null); // Argument list for the invoked method
如果您必须实例化的所有类都公开了您必须调用的相同方法,那么您可以为所有这些类定义一个通用的Interface
:
interface MyInterface
{
void showData();
}
class MyClass : MyInterface
{
public void showData()
{
Console.WriteLine("MyClass");
}
}
class MyClass2 : MyInterface
{
public void showData()
{
Console.WriteLine("MyClass2");
}
}
然后将对象的实例强制转换为MyInterface并调用方法:
// Using MyClass
Type objType = Type.GetType("VsLogAnalyzer." + "MyClass");
MyInterface myObj = Activator.CreateInstance(objType) as MyInterface;
myObj.showData();
// Using MyClass2
objType = Type.GetType("VsLogAnalyzer." + "MyClass2");
myObj = Activator.CreateInstance(objType) as MyInterface;
myObj.showData();
// I had the problem that the program didn't find the specific class
// This is the code that I used and it helped me resolve the exception by entering the namespace also
// the s is the string
Type objType = Type.GetType("Namespace." + s);
object obj = Activator.CreateInstance(objType);
MethodInfo Method = objType.GetMethod("showData");
object Value = Method.Invoke(obj,null);
richTextBox1.Text = Value.ToString();
THX大量@codroipo