C# 方法,该方法在c中接受泛型类作为参数#

C# 方法,该方法在c中接受泛型类作为参数#,c#,generics,C#,Generics,在我的项目中,我有一个泛型类,用于存储数据并传递给另一个函数: public class SqlCommandParameter<T> { public string ParameterName { get;private set; } public SqlDbType SqlDbType { get; private set; } public T SqlDbValue { get; private set; } public SqlCommand

在我的项目中,我有一个泛型类,用于存储数据并传递给另一个函数:

public class SqlCommandParameter<T>
{
    public string ParameterName { get;private set; }
    public SqlDbType SqlDbType { get; private set; }
    public T SqlDbValue { get; private set; }

    public SqlCommandParameter(string parameterName, SqlDbType sqlDbType, T sqlDbValue)
    {
        ParameterName = parameterName;
        SqlDbType = sqlDbType;
        SqlDbValue = sqlDbValue;
    }
}
公共类SqlCommandParameter
{
公共字符串参数名称{get;private set;}
公共SqlDbType SqlDbType{get;private set;}
public T SqlDbValue{get;private set;}
公共SqlCommandParameter(字符串参数名称、SqlDbType SqlDbType、T sqlDbValue)
{
ParameterName=ParameterName;
SqlDbType=SqlDbType;
SqlDbValue=SqlDbValue;
}
}
但当我试图将此实例传递给另一个函数时,它给出了错误:无法解析T。以下是我的方法声明:

 public Task<DataTable> GetDataAsync(int? id, string commandTextQuery, CommandType commandType,params SqlCommandParameter<T>[] parameters )
    { ... } 
公共任务GetDataAsync(int?id、字符串commandTextQuery、CommandType CommandType、params SqlCommandParameter[]参数) { ... }
由于存储过程的数字或值不同,因此我将其作为
params
传递。如何以正确的方式将泛型类传递给函数?有人能建议一种没有错误的方法吗?

您可以将
GetDataAsync()
作为一个通用方法,
GetDataAsync()
但是所有参数都将限于调用该方法时发生的任何
T

GetDataAsync(..., new SqlCommandParameter<int>(), new SqlCommandParameter<int>());
有了上述功能,下面的调用将起作用:

GetDataAsync(..., new SqlCommandParameter<int>(), new SqlCommandParameter<string>());
GetDataAsync(…,新SqlCommandParameter(),新SqlCommandParameter());
如果方法的签名是

public Task<DataTable> GetDataAsync(
    int? id,
    string commandTextQuery,
    CommandType commandType,
    params SqlCommandParameter[] parameters )  { ... }
公共任务GetDataAsync( int?id, 字符串commandTextQuery, 命令类型命令类型, 参数SqlCommandParameter[]参数{…}
另一种解决方案是为泛型参数创建一个容器,并将该容器传递给不带
params
的方法,因为您将只传递一个集合。

GetDataAsync
-除非在方法签名中为T指定类型,否则需要将该方法设为泛型(或者除非它是泛型类中的一个方法。)添加
T
有效,请将其作为答案发布,以便我可以将其标记为已接受answer@sony我不认为
GetDataAsync
是您想要的答案-它将可接受的参数集限制为每次调用仅使用一种类型(除非它正是您想要的)。然后您可以使用dynamic发送参数
GetDataAsync(id、ctq、ct、新SqlCommandParameters(…)、新SqlCommandParameters(…);
GetDataAsync(..., new SqlCommandParameter<int>(), new SqlCommandParameter<string>());
public Task<DataTable> GetDataAsync(
    int? id,
    string commandTextQuery,
    CommandType commandType,
    params SqlCommandParameter[] parameters )  { ... }