getConstructor.invoke 오류
-
03-07-2019 - |
문제
이것은 연구 프로젝트입니다. 세 가지 데이터베이스 클래스 A, B, c가 있습니다. 생성자를 통해 클래스의 객체를 만들 수있는 공장 클래스가 있습니다. 세 가지 클래스 각각 [A, B, C]에는 데이터베이스 연결 객체를 공급하는 매개 변수가있는 생성자가 있습니다. 이것은 공장 클래스의 CreateObject 메소드에서 사용하는 코드입니다.
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;
위의 마지막 줄은이 오류를 제공합니다.
"'System.RuntImeType'유형의 객체 'System.Data.common.dbConnection'유형으로 변환 할 수 없습니다."
'System.RuntImeType'은 어떻게 여기에 왔습니까? 나는 유형 dbconnection의 변수를 취하는 생성자가있는 클래스 A의 객체를 만들려고 노력하고 있습니다.
현재 나는 클래스 A 인스턴스 만 만들기 위해 공장 수업 지침으로 전달합니다. 이것은 클래스 A의 코드입니다.
public class SqlServerDB: Database
{
string str = "";
public SqlServerDB(DbConnection DBConn)
: base(DBConn)
{
str = "SQLServer";
}
}
내가 뭘 잘못하고 있죠?
감사.
해결책
호출 메소드가 사물) 생성자로 전달해야합니다. 당신은 유형 DBConnection. 당신이 전달해야 할 것은 dbconnection의 인스턴스입니다.
좀 더 명확하게 말하면,이 객체 중 하나를 직접 만들고 있다면 다음과 같은 일을 할 것입니다.
DbConnection connection = GetConnection(); //some method that gives you back a connection object
SqlServerDB db = new SqlServerDB(connection);
그래도하고있는 일은 다음과 같습니다.
Type type = typeof(DbConnection);
SqlServerDB db = new SqlServerDB(type); //This is obviously wrong.
제휴하지 않습니다 StackOverflow