如何从方法返回一个字符串

Ing*_*guX -6 c# string

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

例:

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

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

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

Som*_*ved 8

public string myvoid(string key, bool data)
{
    return key + " = " + data;
}
Run Code Online (Sandbox Code Playgroud)

此外,您的方法不应再被调用myvoid,因为它实际上返回一个值.有点像FormatValue会更好.

  • @lc.`+`应该照顾好 (2认同)
  • @lc.:没有...但它*将*按照CLS大写.http://ideone.com/VoWo1 (2认同)

Shy*_*yju 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"; 
}
Run Code Online (Sandbox Code Playgroud)

正如奥斯丁在评论中提到的那样,这将更加清洁

public string myvoid(string key , bool data)
{
   return string.Format("{0} = {1}", key, data);
}
Run Code Online (Sandbox Code Playgroud)

  • `return string.Format("{0} = {1}",key,data);` (2认同)