2013-03-26 67 views
1

我需要大大减少这段代码,有没有什么办法可以创建一个描述其方向的sql参数? 这里是代码:有什么办法可以减少这个ado.net代码吗?

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) 

在此先感谢。

+2

我看到3台4个几乎相同的代码行。创建一个方法并传入参数,以便可以改变。 – 2013-03-26 18:49:09

回答

1

有一个overload of the constructor that includes the direction,但你必须指定很多其他参数,所以代码毕竟不会太短。

您可以扩展方法:

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()) 
2

对于每一个参数,你可以使用

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 _ 
}) 
1

尝试:

command.Parameters.Add(new SqlParameter("@ROJO", SqlDbType.Int) With {.Direction = ParameterDirection.Output}); 
相关问题