-6

如何将值作为文本而不是返回void

例子:

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = myvoid("foo", true);
    // Error: Cannot implicitly convert type void to string
}

public void myvoid(string key , bool data)
{
    if (data == true)
    {
        string a = key + " = true";
        MessageBox.Show(a); // How can I export this value to labe1.Text?
    }
    else
    {
        string a = key + " = false";
        MessageBox.Show(a); // How can I export this value to labe1.Text?
    }
}

如何a从返回 void 的方法中分配值,而不是显示消息框,并将其应用于label1.Text

4

6 回答 6

8

利用:

public string myvoid(string key, bool data)
{
    return key + " = " + data;
}

此外,不应再调用您的方法,myvoid因为它实际上返回一个值。类似的东西FormatValue会更好。

于 2012-07-19T16:53:46.947 回答
5
private void button1_Click(object sender, EventArgs e)
{
    label1.Text = myvoid("foo", true);
}

public string myvoid(string key , bool data)
{
    if (data)       
        return key + " = true";         
    else       
        return  key + " = false"; 
}

正如奥斯汀在评论中提到的那样,这会更干净

public string myvoid(string key , bool data)
{
   return string.Format("{0} = {1}", key, data);
}
于 2012-07-19T16:53:16.210 回答
3

将返回类型更改为字符串:

 public string myvoid(string key, bool data)
 {
    string a = string.Empty;
    if (data == true)
    {
        a = key + " = true";
        MessageBox.Show(a); // How can I export this value to labe1.Text?
    }
    else
    {
        a = key + " = false";
        MessageBox.Show(a); // How can I export this value to labe1.Text?
    }
    return a;
 }
于 2012-07-19T16:51:32.233 回答
1

您必须将方法的返回类型更改为字符串。

像这样:public string myvoid(string key , bool data)

然后返回字符串 a;

像这样:

return a;
于 2012-07-19T16:54:39.967 回答
0

使用字符串返回类型:

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = myvoid("foo", true);
}

public string myvoid(string key, bool data)
{
    string a = string.Empty;
    if (data == true)
    {
        a = key + " = true";
        MessageBox.Show(a);
    }
    else
    {
        a = key + " = false";
        MessageBox.Show(a);
    }
    return a;
 }

如果你想坚持空虚,你可以这样做

 private void button1_Click(object sender, EventArgs e)
 {
     myvoid("foo", true , label1);
 }

 public void myvoid(string key, bool data, label lb)
 {
     string a = string.Empty;
     if (data == true)
     {
         a = key + " = true";
         MessageBox.Show(a);
     }
     else
     {
         a = key + " = false";
         MessageBox.Show(a);
     }

     lb.Text = a;
 }
于 2012-07-19T17:20:02.613 回答
0

查看http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx

如果你真的想使用 a void,你可以out为此使用谓词。

于 2012-07-19T16:55:35.740 回答