VB到C#可选参数

时间:2014-08-06 16:15:19

标签: c# vb.net

我一直在寻找解决方案,但还没有得到一个可靠的答案。我有VB代码,我需要转换为c#。这是VB代码。我尝试了不同的解决方案,但似乎都没有。这是函数的定义

Protected Sub LoadData(ByVal ProcedureName As String, ByVal NumOuts As Long, ByRef Label1 As Label, Optional ByRef Label2 As Label = Nothing, Optional ByRef Label3 As Label = Nothing)

    Dim ConnStr As String

    ConnStr = "Data Source=H50;Initial Catalog=" + Me.DatabaseName.Text + ";Integrated Security=True"
    Dim conn As New SqlConnection(ConnStr).....

这是调用此

的众多功能之一
Protected Sub LoadtblStaffContactsBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LoadtblStaffContactsBtn.Click
    LoadData("Load_tblStaffContacts", 2, Me.tblStaffContacts_Label1, Me.tblStaffContacts_Label2)
    Me.LoadtblStudentBtn.Enabled = True
End Sub

4 个答案:

答案 0 :(得分:6)

您通过引用传递可选参数,这在C#中是不可能的。

除非您实际更改方法中的标签引用(这似乎极不可能),否则这些参数不应该首先通过引用传递。

只需按正常值传递参数,并通过指定值使其成为可选项:

protected void LoadData(string ProcedureName, long NumOuts, Label Label1, Label Label2 = null, Label Label3 = null) {

答案 1 :(得分:1)

你应该使用默认参数,例如使用null

private void TestFunc(string s1, string s2 = null)
{
}

这样打电话:

TestFunc("s1");

TestFunc("s1", "s2");

答案 2 :(得分:0)

非常简单。在C#中使用null代替VB.NET Nothing,但是你可以使用任何值作为默认值。

只需确保它们是尾随参数,并像分配局部变量一样分配值。

public void foo(int a, string b, string c = "something", object t = null)
{

}

答案 3 :(得分:0)

试试这个:

Protected void LoadData(out string ProcedureName, out long NumOuts, ref label Label1,          ref label Label1 = null, ref label Label3 = null){
    string Connstr;
    ConnStr = // Connection String;
    SqlConnection conn = new SqlConnection(Connstr).......
}

以下是处理按钮点击事件。

Button1.Click += (object sender, System.EventArgs e)=>
{
    LoadData("Load_tblStaffContacts", 2, this.tblStaffContacts_Label1, this.tblStaffContacts_Label2);
 this.LoadtblStudentBtn.Enabled = true;
}