如何将值作为文本而不是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?
}
}
如何从返回void的方法中指定值a,而不是显示消息框,并将其应用于label1.Text
?
答案 0 :(得分:8)
public string myvoid(string key, bool data)
{
return key + " = " + data;
}
此外,您的方法不应再被称为myvoid
,因为它实际上会返回一个值。像FormatValue
这样的东西会更好。
答案 1 :(得分: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";
}
评论中提到的Austin,这将更加干净
public string myvoid(string key , bool data)
{
return string.Format("{0} = {1}", key, data);
}
答案 2 :(得分:3)
将返回类型更改为字符串
public string myvoid(string key , bool data)
{
string a = string.Empty;
if (data == true)
{
a = key + " = true";
MessageBox.Show(a);//How to export this value to labe1.Text
}
else
{
a = key + " = false";
MessageBox.Show(a);//How to export this value to labe1.Text
}
return a;
}
答案 3 :(得分:1)
您必须将方法的返回类型更改为字符串
像这样:public string myvoid(string key , bool data)
然后返回字符串a;
像这样:return a;
答案 4 :(得分:0)
查看http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx。
如果您真的想使用void
,可以使用out
谓词。
答案 5 :(得分: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;
}