GetConstructor.invoke错误 [英] GetConstructor.invoke error

查看:103
本文介绍了GetConstructor.invoke错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个研究项目.我有三个数据库类A,B,C.有一个工厂类通过其构造函数接收要创建哪个类的对象.这三个类[A,B,C]中的每一个都有一个构造函数,该构造函数的参数提供数据库连接对象.这是我在工厂类的createObject方法中使用的代码:

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.

" 类型'System.RuntimeType'的对象不能转换为类型'System.Data.Common.DbConnection'. "

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

"System.RuntimeType"如何到达这里?我正在尝试创建一个类A的对象,该对象的构造函数采用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.

当前,我正在传递给工厂类说明以仅创建类A的实例.这是A类的代码:

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";
    }
}

我做错了什么?

谢谢.

推荐答案

Invoke方法采用您需要传递给构造函数的对象.您正在传递类型 DbConnection.您应该传递的是DbConnection的实例.

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.

这篇关于GetConstructor.invoke错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆