2012-04-03 33 views
0

我已经创建了一个名为ExecuteProcedure<T>(T command, string parameters)一个通用的功能,现在ExecuteProcedure功能里面我想投的T into SqlCommand,这样我可以使用SqlCommand's属性,如Parameters.Add()这里是我的代码。从通用牛逼获取的SqlCommand类型在.NET

T could be SqlCommand or SqlDataAdapter 

这里是我的代码:

public void ExecuteProcedure<T>(T command, string parameters) 
{ 
    using (connection) 
    { 
     if (typeof(T) == typeof(SqlCommand)) 
     { 
      //how to convert into SqlCommand Here to use command.CommandType Property below. 
     } 
     command.CommandType = CommandType.StoredProcedure; 
     foreach (string param in parameters.Split(',')) 
     { 
      SqlParameter par = new SqlParameter(param, param.Substring(1, param.Length - 1)); 
      command.Parameters.Add(par); 
     } 


     connection.Open(); 
     command.ExecuteNonQuery(); 
    } 
} 

回答

0

您可以使用此代码投吨至SqlCommand的

SqlCommand cmd = (SqlCommand)Convert.ChangeType(command, typeof(SqlCommand)); 

反正谢谢@Chris

0

我相信所有你需要做的是:

SqlCommand cmd = (SqlCommand)(object)command; 
+0

hi @Chris,我试过,但它不工作,它会引发编译时错误,说不能将类型T转换为System.Data.SqlClient.SqlCommand – Abbas 2012-04-03 23:31:53

+0

啊,是的,没有约束。尝试将对象转换为已知类型。答案已更新。 – 2012-04-03 23:39:36