GetConstructor.invoke error

半世苍凉 提交于 2020-01-06 02:55:31

问题


This is a study project. I have three database classes A,B,C. There is a factory class that receives thru its constructor which class's object to create. Each of the three classes[A,B,C] has a constructor with a parameter to supply the database connection object. This is the code I'm using in the factory class's createObject method:

Type classtyp = Type.GetType(className);

Type[] constrParam = new Type[1];
constrParam[0] = typeof(DBConnection);
ConstructorInfo constr = database.GetConstructor(constrParam);

return constr.Invoke(constrParam) as Database;

The last line above gives this error.

"Object of type 'System.RuntimeType' cannot be converted to type 'System.Data.Common.DbConnection'."

How did the 'System.RuntimeType' get here? I'm trying to create an object of class A which has a constructor that takes a variable of type DBconnection.

Currently I'm passing to the factory class instructions to create an instance of class A only. This the code of class A:

public class SqlServerDB: Database
{
    string str = "";

    public SqlServerDB(DbConnection DBConn)
        : base(DBConn)
    {
        str = "SQLServer";
    }
}

What am I doing wrong?

Thanks.


回答1:


The Invoke method takes the object(s) that you need to pass into the constructor. You're passing in the type DbConnection. What you should be passing in, is an instance of DbConnection.

To be a bit more clear, if you were directly creating one of these objects, you'd do something like this:

DbConnection connection = GetConnection(); //some method that gives you back a connection object
SqlServerDB db = new SqlServerDB(connection);

What you're doing though is the same as doing this:

Type type = typeof(DbConnection);
SqlServerDB db = new SqlServerDB(type); //This is obviously wrong.


来源:https://stackoverflow.com/questions/812662/getconstructor-invoke-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!