如何在泛型方法中声明泛型变量?

时间:2016-12-23 16:30:47

标签: c# class generics methods

我想知道是否可以在泛型方法中声明泛型变量。在下面的代码中,我试图使“结果”成为一个通用变量,但我很难这样做。因此,我将不胜感激任何帮助。提前致谢

    public static T GetSQLResults<T>(string StoredProcName, Dictionary<string, string> StoredProcParameters)
    {
        var results;

        using (SqlConnection conn = new SqlConnection(Settings.ConnStringDb))
        {
            using (SqlCommand cmd = new SqlCommand(StoredProcName, conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                foreach (var param in StoredProcParameters)
                {
                    cmd.Parameters.AddWithValue(param.Key, param.Value);
                }

                conn.Open();
                if (typeof(T) == typeof(Boolean))
                {
                    results = cmd.ExecuteReader().HasRows;
                }
                else if (typeof(T) == typeof(DataTable))
                {
                    results.Load(cmd.ExecuteReader());
                }

                //results.Load(cmd.ExecuteReader());
                conn.Close();
            }

            return (T)Convert.ChangeType(results, typeof(T));
        }
    }

0 个答案:

没有答案