1

我需要显着减少这段代码,有没有办法创建一个描述其方向的sql参数?这是代码:

    Dim Oparam1 As SqlParameter = New SqlParameter("@ROJO", SqlDbType.Int)
    Dim Oparam2 As SqlParameter = New SqlParameter("@AMBAR", SqlDbType.Int)
    Dim Oparam3 As SqlParameter = New SqlParameter("@AMARILLO", SqlDbType.Int)
    Dim Oparam4 As SqlParameter = New SqlParameter("@VERDE", SqlDbType.Int)
    Oparam1.Direction = ParameterDirection.Output
    Oparam2.Direction = ParameterDirection.Output
    Oparam3.Direction = ParameterDirection.Output
    Oparam4.Direction = ParameterDirection.Output
    command.Parameters.Add(Oparam1)
    command.Parameters.Add(Oparam2)
    command.Parameters.Add(Oparam3)
    command.Parameters.Add(Oparam4)

提前致谢。

4

3 回答 3

2

For each parameter you could use

C#

command.Parameters.Add(new SqlParameter("@name", SqlDbType.Int)
    {Direction = ParameterDirection.Output});

VB.NET

command.Parameters.Add(New SqlParameter("@name", SqlDbType.Int) With { _
    .Direction = ParameterDirection.Output _
})
于 2013-03-26T18:50:02.817 回答
1

尝试:

command.Parameters.Add(new SqlParameter("@ROJO", SqlDbType.Int) With {.Direction = ParameterDirection.Output});
于 2013-03-26T18:52:10.607 回答
1

有一个包含方向的构造函数的重载,但是你必须指定很多其他参数,所以代码毕竟不会更短。

你可以做一个扩展方法:

Imports System.Runtime.CompilerServices

Module SqlExtensions

  <Extension()>
  Public Function SetOutput(parameter As SqlParameter) As SqlParameter
    parameter.Direction = ParameterDirection.Output
    Return parameter
  End Function

End Module

现在您可以在参数上使用它:

command.Parameters.Add(New SqlParameter("@ROJO", SqlDbType.Int).SetOutput())
command.Parameters.Add(New SqlParameter("@AMBAR", SqlDbType.Int).SetOutput())
command.Parameters.Add(New SqlParameter("@AMARILLO", SqlDbType.Int).SetOutput())
command.Parameters.Add(New SqlParameter("@VERDE", SqlDbType.Int).SetOutput())
于 2013-03-26T19:00:21.027 回答