如何从方法返回字符串
如何返回值作为文本而不是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?
}
}
如何可以从返回而不是显示一个消息框空隙,一个方法分配值,并将其应用到label1.Text
?
更改返回类型为字符串
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;
}
范围,范围,范围。 – Ryan 2012-07-19 16:53:00
除了在if语句之前声明'string a' ... – 2012-07-19 16:53:32
我错过了为什么在这个downvotes ...它看起来像我们现在必须服务整个代码在银盘上它被upvoted? – 2012-07-19 16:54:36
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);
}
'return string.Format(“{0} = {1}”,key,data);' – 2012-07-19 16:53:56
'label1.Text = MessageBox.Show(myvoid(“foo”,true))'错误 – SomeWritesReserved 2012-07-19 16:57:24
@SomeWritesReserved:Yea 。刚刚纠正。我没有注意到标签!谢谢:) – Shyju 2012-07-19 16:59:18
public string myvoid(string key, bool data)
{
return key + " = " + data;
}
而且你的方法不应该叫myvoid
因为它实际上返回一个值。像FormatValue
会更好。
,你将有你的方法的返回类型更改为字符串
这样的:public string myvoid(string key , bool data)
,然后返回字符串;
这样的:
return a;
使用字符串返回类型
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;
}
'== == TRUE'坏 – Ryan 2012-07-19 16:52:34
我看到了'void' – 2012-07-19 16:55:24
好,不返回一个void,返回一个字符串..! – 2012-07-19 16:58:35