【问题标题】:Getting the SqlCommand Type from Generic T in .net从 .net 中的 Generic T 获取 SqlCommand 类型
【发布时间】:2012-04-03 23:23:19
【问题描述】:

我创建了一个名为ExecuteProcedure<T>(T command, string parameters) 的通用函数,现在在ExecuteProcedure 函数中我想转换T into SqlCommand,这样我就可以使用SqlCommand's 属性,如Parameters.Add() 这是我的代码。

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();
    }
}

【问题讨论】:

    标签: function generics c#-2.0


    【解决方案1】:

    我相信你所要做的就是:

    SqlCommand cmd = (SqlCommand)(object)command;
    

    【讨论】:

    • 嗨@Chris,我试过了,但它不起作用,它抛出编译时错误,说不能将类型 T 转换为 System.Data.SqlClient.SqlCommand
    • 啊,是的,没有限制。尝试转换为“对象”,然后转换为已知类型。答案已更新。
    【解决方案2】:

    您可以使用此代码将 T 转换为 SqlCommand

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

    无论如何感谢@Chris

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      • 1970-01-01
      相关资源
      最近更新 更多