[英]Using Switch case with Equals method in C#
Is there a way to convert the below if else condition into Switch in C#. 有没有办法将下面的if else条件转换为C#中的Switch。 I am using Equals method for checking the type, but unable to convert to switch case.
我使用Equals方法检查类型,但无法转换为switch case。
if (fi.FieldType.Equals(typeof(int)))
{
fi.SetValue(data, BitConverter.ToInt32(buffer, 0));
}
else if (fi.FieldType.Equals(typeof(bool)))
{
fi.SetValue(data, BitConverter.ToBoolean(buffer, 0));
}
else if (fi.FieldType.Equals(typeof(string)))
{
byte[] tmp = new byte[la.length];
Array.Copy(buffer, tmp, tmp.Length);
fi.SetValue(data, System.Text.Encoding.UTF8.GetString(tmp));
}
else if (fi.FieldType.Equals(typeof(double)))
{
fi.SetValue(data, BitConverter.ToDouble(buffer, 0));
}
else if (fi.FieldType.Equals(typeof(short)))
{
fi.SetValue(data, BitConverter.ToInt16(buffer, 0));
}
Please help us.... 请帮助我们....
With C# 7 pattern matching you can do this: 使用C#7 模式匹配,您可以执行以下操作:
switch (fi.FieldType)
{
case var _ when fi.FieldType.Equals(typeof(int)):
fi.SetValue(data, BitConverter.ToInt32(buffer, 0));
break;
case var _ when fi.FieldType.Equals(typeof(bool)):
fi.SetValue(data, BitConverter.ToBoolean(buffer, 0));
break;
//etc
}
Note that this is using _
to discard the value as we don't care about it. 请注意,这是使用
_
来丢弃该值,因为我们不关心它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.