将对象名称作为字符串给出时,如何声明和调用C#对象?

时间:2015-07-24 07:09:09

标签: c# string class object reflection

因为我没有输入命名空间+类的名称(我只输入了类名),我收到了异常错误。

我写了很多课,我收到了一个字符串。我想直接声明并启动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();


      }



}

2 个答案:

答案 0 :(得分:1)

您必须使用反射,但是您需要一个完全限定的类名,因此如果您只有类名,则必须确定默认命名空间:

Automatic Builds

如果您必须实例化的所有类都公开了您必须调用的相同方法,则可以为所有这些类定义公共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

然后将对象的实例强制转换为MyInterface并调用方法:

interface MyInterface
{
    void showData();
}

class MyClass : MyInterface
{

    public void showData()
    {
        Console.WriteLine("MyClass");
    }
}

class MyClass2 : MyInterface
{
    public void showData()
    {
        Console.WriteLine("MyClass2");
    }
}

答案 1 :(得分:0)

  // 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