[英]C# - Is Statement in Switch Statement
我需要检查大量控件是否包含值或它们是否已留空。
我希望做这样的事情:
public static bool IsObjectEmpty(Control ctrlThis)
{
switch (ctrlThis)
{
case ctrlThis is TextBox:
TextBox txtThis = (TextBox)ctrlThis;
if (txtThis.Text == "" || txtThis.Text == null)
{ return false; }
break;
case (ctrlThis is ComboBox):
ComboBox cboThis = (ComboBox)ctrlThis;
if (cboThis.SelectedValue == -1)
{ return false; }
break;
case (ctrlThis is NumericUpDown):
NumericUpDown numThis = (NumericUpDown)ctrlThis;
if (numThis.Value == 0)
{ return false; }
break;
etc etc...
但这不能编译:
Error 3 A switch expression or case label must be a bool, char, string,
integral, enum, or corresponding nullable type
有没有办法在 switch 语句中做到这一点,或者我只需要做大量的 if / else if 东西? Google 和 StackOverflow 搜索并没有多大用处。
Case
标签可以只包含常量表达式。
所以在你的回答中不是 const 表达式。
它是一个评估值。
就像你做不到的一样
public const int a=Enumerable.Range(0,2).First();
您可以在 switch case 之前计算这些值
然后将它们与一个值进行比较。
就像是
var t=(ctrlThis is ComboBox)
...
...
switch ( t) ...
case true :...
switch-label:
case constant-expression :
default :
如果你不这样做,编译器会尖叫:
期望一个恒定值
例子 :
switch (myInt)
{
case (2+Enumerable.Range(0,2).First()):
return true;
default:
return true;
}
基于类型的条件(if/switch)大多是个坏主意。
这种方法怎么样:
public static bool IsObjectEmpty(TextBox ctrlThis)
{
if (ctrlThis.Text == "" || ctrlThis.Text == null) {
return false;
}
etc etc...
}
public static bool IsObjectEmpty(ComboBox ctrlThis)
{
if (ctrlThis.SelectedValue == -1) {
return false;
}
etc etc...
}
public static bool IsObjectEmpty(NumericUpDown ctrlThis)
{
if (ctrlThis.Value == 0) {
return false;
}
etc etc...
}
你可以做:
switch (ctrlThis.GetType().ToString())
{
case "System.Windows.Forms.TextBox" :
TextBox txtThis = (TextBox)ctrlThis;
if (txtThis.Text == "" || txtThis.Text == null)
{ return false; }
break;
}
我也可能会使用 if 语句,例如:
public static bool IsObjectEmpty(Control ctrlThis)
{
if (ctrlThis is TextBox)
{
TextBox txtThis = (TextBox)ctrlThis;
if (txtThis.Text == "" || txtThis.Text == null)
return false;
}
else if (ctrlThis is ComboBox)
{
ComboBox cboThis = (ComboBox)ctrlThis;
if (int.Parse(cboThis.SelectedValue.ToString()) == -1)
return false;
}
else if (ctrlThis is NumericUpDown)
{
NumericUpDown numThis = (NumericUpDown)ctrlThis;
if (numThis.Value == 0)
return false;
}
else
{
//Serves as 'default' in the switch
}
return true;
}
据我所知你可以这样做
public static bool IsObjectEmpty(Control ctrlThis)
{
Type t = ctrlThis.GetType();
switch (t)
{
case typeof(TextBox):
TextBox txtThis = (TextBox)ctrlThis;
if (txtThis.Text == "" || txtThis.Text == null)
{ return false; }
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.