从字符串值创建Class实例并在C#中分配给相同的类类型

时间:2014-06-05 12:25:46

标签: c#

private void QueryDBSchema()
    {
        // Schema information for the current database connection.
        DataTable schema;

        // Loop counter.
        int loop = 0;

        // Clean up the menu so the menu item does not hang while this function  executes.
        this.Refresh();


            // Instantiate an OleDbConnection object.
        using (OleDbConnection oleDbConnection = new    OleDbConnection("Provider=SQLOLEDB;Password=sa123;User ID=sa;Data Source=mukesh;Initial Catalog=Medi;"))
            {
                try
                {
                    // Open the connection.
                    oleDbConnection.Open();

                    // Retrieve the Table objects.
                        schema =    oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "table" });

                    // Store the table names in the object collection.
                    for (loop = 0; loop < schema.Rows.Count; loop++)
                    {
                        objects.Add(schema.Rows[loop].ItemArray[2].ToString());
                    }
                }
                catch (Exception e)
                {
                   // Messages.BadConnection(e);
                }
            }

    }

此功能用于在对象列表中获取表名。

        // Instantiate the objects collection.
        this.objects = new Collection<string>();
        QueryDBSchema();

        // Gather each of the selected items (if any) into a collection object.
        foreach (string item in this.objects)
          {
          //This should be like this
          // "item" obj = new "item";

          }

在foreach循环中我想创建带有保存在项值中的字符串的类对象。如果这可能在c#中,同一名称类在不同的命名空间中退出,我想将对象分配给不同命名空间中的另一个相同的类并调用函数命名为像obj1中的保存。

,例如

//&#34; item&#34; obj1 = new&#34; item&#34 ;; //&#34;项目&#34; obj2 = new&#34; item&#34 ;;

OBJ1 = OBJ2; obj1.Save();

1 个答案:

答案 0 :(得分:0)

使用

ObjectHandle handle = Activator.CreateInstance(&#34; YourAssemblyName_String&#34;,&#34; Item&#34;);

项目obj =(Item)handle.Unwrap();