【问题标题】:Call GetStoredProcCommand with variable number of arguments in C#?在 C# 中使用可变数量的参数调用 GetStoredProcCommand?
【发布时间】:2012-10-06 14:58:28
【问题描述】:

在我的代码中,我一直在重复这样的代码块:

var returnData = MyDb.ExecuteDataSet(
    MyDb.GetStoredProcCommand("MyTable_Insert", columnOne, columnTwo, columnThree),
    transaction
);

var returnId = (int)returnData.Tables[0].Rows[0]["INSERTED_ID"];

在我看来,这是一个相当大的代码块,要重复很多次,但我不知道如何将其概括为方法,因为每个存储过程的参数数量不同。

(对我而言)显而易见的解决方案是将我的参数传递给数组中的函数,然后将它们展开以调用 GetStoredProcCommand,但我找不到这样做的方法:

private int CallStoredProcedure(string procName, List<dynamic> parameterValues) {
    ..
    MyDb.GetStoredProcCommand(procName, expand parameterValues);
    // ERROR: Obviously "expand" doesn't exist
    ..
}

我可以使用 AddInParameter 来传递参数的冗长方式,但是我需要将类型信息与参数值一起传递:

private int CallStoredProcedure(string procName, IDictionary<DbType, IDictionary<string, string>> paramsKeyValuesByType) {
    ..
    MyDb.AddInParameter(myProcCommand, param.Value.Key, param.Key, param.Value.Value);
    ..
}

但是我必须在调用该方法之前构造IDictionary 对象,这比我最初调用该过程的方式更加冗长。

谁能想到一个优雅的解决方案?

【问题讨论】:

  • 如果您在MyDb.GetStoredProcCommand 中使用可变参数,为什么不在CallStoredProcedure 中也使用可变参数?变量参数存储在一个数组中,可以直接传递而不是扩展列表。
  • 您确定您的意思是dynamic 而不是object

标签: c# .net arguments enterprise-library system.data


【解决方案1】:

您可以使用params 关键字:

private int CallStoredProcedure(string procName, params object[] parameterValues) {
    ..
    MyDb.GetStoredProcCommand(procName, parameterValues);
    ..
}

【讨论】:

  • 我认为这对我没有帮助,因为我如何将这些变量参数传递给GetStoredProcCommand - 不是必须使用params 关键字来定义吗?我无法让它以这种方式工作。我很高兴得到纠正。
  • @RobinWinslow:你不需要做任何事情。检查documentation。如您所见,GetStoredProcCommand 也使用了params,所以它应该可以正常工作。为什么你认为它行不通?你试过了吗?你得到了什么错误?
  • 好点。整个params 的事情让我有点困惑,但现在我明白了。
猜你喜欢
  • 2011-07-09
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多