c# switch statement is return suitable to replace break(c#switch语句是return适合替换break)
问题描述
这是处理 c# switch 语句的适当方法还是仍然需要显式中断?参考
Is this an appropriate way to handle c# switch statements or is an explicit break required still? reference
public static string ToRegistryString(AliceKey.AliceKeyPaths aliceKeyPath)
{
switch (aliceKeyPath)
{
case AliceKey.AliceKeyPaths.NET_CLR_DATA:
return @".NET CLR Data";
case AliceKey.AliceKeyPaths.NET_CLR_NETWORKING:
return @".NET CLR Networking";
case AliceKey.AliceKeyPaths.NET_DATA_PROVIDER_MSSQL:
return @".NET Data Provider for SqlServer";
case AliceKey.AliceKeyPaths.NET_DATA_PROVIDER_ORACLE:
return @".NET Data Provider for Oracle";
}
return new string(new char[0]);
}
推荐答案
没关系.关键是 case 块的结尾应该是无法到达的——它就在这里,因为你已经返回了.
That's fine. The point is that the end of a case block should be unreachable - which it is here, because you've returned.
你为什么返回 new string(new char[0])
而不仅仅是 "" 或 string.Empty
呢?如果你试图确保它每次都是不同的字符串,你实际上会遇到一个非常奇怪的极端情况——尽管调用 new string(...)
该代码实际上总是会返回相同的参考...
Why are you returning new string(new char[0])
rather than just "" or string.Empty
though? If you're trying to make sure it's a different string each time, you'll actually run into a very weird corner case - despite calling new string(...)
that code will always actually return the same reference...
最后:我实际上建议将此 switch/case 块更改为 Dictionary<AliceKey.AliceKeyPaths, string>
:
Finally: I would actually suggest changing this switch/case block into just a Dictionary<AliceKey.AliceKeyPaths, string>
:
private static readonly Dictionary<AliceKey.AliceKeyPaths, string> RegistryMap =
new Dictionary<AliceKey.AliceKeyPaths, string>
{
{ AliceKey.AliceKeyPaths.NET_CLR_DATA, @".NET CLR Data" },
{ AliceKey.AliceKeyPaths.NET_CLR_NETWORKING, @".NET CLR Networking" },
// etc
};
public static string ToRegistryString(AliceKey.AliceKeyPaths aliceKeyPath)
{
string value;
return RegistryMap.TryGetValue(aliceKeyPath, out value) ? value : "";
}
这篇关于c#switch语句是return适合替换break的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c#switch语句是return适合替换break


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01