我想知道我是否可以缩短它:
bool Check()
{
return textBox1.Text.All(char.IsDigit) ? true : Falsepath();
}
bool Falsepath()
{
MessageBox.Show("The data you entered is incorrect","Error",MessageBoxButtons.OK);
return false;
}
像这样:
bool Check()
{
return textBox1.Text.All(char.IsDigit) ? true : (sender, e) =>
{
MessageBox.Show("The data you entered is incorrect", "Error", MessageBoxButtons.OK);
return false;
};
}
当然,我输入的第二个代码是不正确的,但我以它为例。
那么,我可以在检查某些内容时执行代码还是必须使用单独的函数?
最佳答案
你可以这样写:
bool Check()
{
return textBox1.Text.All(char.IsDigit) ?
true :
((Func<bool>)(() =>
{
MessageBox.Show("The data you entered is incorrect", "Error", MessageBoxButtons.OK);
return false;
}))();
}
但这很糟糕,请不要这样做!...
遗憾的是,在 C# 中,您必须显式地告诉编译器匿名函数的类型。这使一切变得更加复杂。看 Actor (Func<bool>)
?在 Javascript 中你不需要它,事实上在那种语言中它是一种常见的模式。在 C# 中不是因为它不可读且丑陋。
注意最后的()
执行匿名方法。
请注意,在这种特殊情况下,您可以这样写:
bool Check()
{
return textBox1.Text.All(char.IsDigit) ?
true :
MessageBox.Show("The data you entered is incorrect", "Error", MessageBoxButtons.OK) == DialogResult.Abort;
}
所以调用MessageBox.Show()
并以比较为 false
的方式比较其结果.
关于c# - 我可以在返回值时执行代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30142071/