gpt4 book ai didi

c# - 带有类型检查 C# 的更好的 If 语句

转载 作者:太空狗 更新时间:2023-10-30 00:02:35 25 4
gpt4 key购买 nike

我目前正在开发 .NET 4.7.1 应用程序。我有一个 If 语句来检查数据类型并相应地调用处理程序方法。

我当前的 If 语句如下所示:

// object msg = MyHelper.Deserialize(xmlString);

if (msg is Tomato) Handle_Tomato((Tomato)msg);
if (msg is Apple) Handle_Apple((Apple)msg);
if (msg is Banana) Handle_Banana((Banana)msg);
if (msg is Orange) Handle_Orange((Orange)msg);

msg 基本上是一个从字符串反序列化的对象。

我在想,是否有更好的方法来编写我的 if 语句?

非常感谢!

最佳答案

作为Sweeper在评论中提到,从 C# 7.0 您可以使用 The is type pattern expression

if (msg is Tomato tomato) Handle_Tomato(tomato);

你也可以使用 pattern matching with a switch statement (Type pattern)C# 7.0

The type pattern enables concise type evaluation and conversion. When used with the switch statement to perform pattern matching, it tests whether an expression can be converted to a specified type and, if it can be, casts it to a variable of that type.

switch(msg)
{
case Tomato tomato : Handle_Tomato(tomato); break;
case Apple apple : Handle_Apple(apple); break;
...
}

关于c# - 带有类型检查 C# 的更好的 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56801916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com