被这个问题困了很长时间。
给出类名(string),如何动态创建(字符串名的)对象
例如下边代码:Exe_Class函数里应该如何写?namespace ConsoleApplication_dynamic_obj
{
    class Program
    {
        static void Main(string[] args)
        {
            //Exe_Class("test");
            Exe_Class("test1");
        }        static void Exe_Class(string class_name)
        {
        }
    }    public class test
    {
        public test()
        {
            Console.WriteLine("test");
        }    }    public class test1
    {
        public test1()
        {
            Console.WriteLine("test1");
        }
    }
}

解决方案 »

  1.   

     static void Exe_Class(string class_name) 

      object obj= Type.GetType(class_name).Assembly.CreateInstance(class_name);

      

  2.   

    using System;
    using System.Collections.Generic;
    using System.Text;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Exe_Class("test1");
            }        static void Exe_Class(string class_name)
            {
                Activator.CreateInstance(null, "ConsoleApplication1." + class_name);
                Console.Read();
            }    }    public class test
        {
            public test()
            {
                Console.WriteLine("test");
            }    }    public class test1
        {
            public test1()
            {
                Console.WriteLine("test1");
            }
        }
    }
      

  3.   

    好像GetType(class_name)中的class_name参数需要补上命名空间,而且这样实现不了,输出“test”或者“test1”,因为在创建类的对象的时候只有new才会调用构造函数,用反射创建类对象的时候不会调用构造函数的。它采用的是另一种机制。
      

  4.   

    示例:string s = "System.Windows.Forms.Form, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";Type t = Type.GetType(s);
    (t.Assembly.CreateInstance(t.FullName) as Form).Show();// string s = "System.Windows.Forms.Form"; 则无法获取 Type t
    // 可见 LZ 所传递的 class_name 的准确性是程序正确运行的保证
      

  5.   

    TO wartim:能用啊,谢谢你
    不过如果我还想调用类里一个方法呢?
      

  6.   

    using System;
    using System.Collections.Generic;
    using System.Text;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Exe_Class("test1");
            }        static void Exe_Class(string class_name)
            {
                Activator.CreateInstance(null, "ConsoleApplication1." + class_name);
                Console.Read();
            }    }    public class test
        {
            public test()
            {
                Console.WriteLine("test");
            }    }    public class test1
        {
            public test1()
            {
                Console.WriteLine("test1");
            }
        }
    }
      

  7.   


    Type.GetType(className).InvokeMember(".ator", BindingFlags.CreateInstance, null, null, args);执行类名对应的类的构造函数
      

  8.   

    用emit比反射好一些吧效率多少得考虑一下