C# switch语句中的return适合代替break
这是处理 C# switch 语句的适当方法还是仍然需要显式中断? 参考
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]);
}
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]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没关系。关键是 case 块的末尾应该是无法到达的 - 它就在这里,因为你已经返回了。
为什么你返回
new string(new char[0])
而不仅仅是 "" 或string.Empty
?如果你试图确保每次都是不同的字符串,你实际上会遇到一个非常奇怪的极端情况 - 尽管调用new string(...)
该代码实际上总是返回相同的参考...最后:我实际上建议将此 switch/case 块更改为
Dictionary
:That's fine. The point is that the end of a case block should be unreachable - which it is here, because you've returned.
Why are you returning
new string(new char[0])
rather than just "" orstring.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 callingnew string(...)
that code will always actually return the same reference...Finally: I would actually suggest changing this switch/case block into just a
Dictionary<AliceKey.AliceKeyPaths, string>
:您不需要专门使用
break
语句,只需使用一个改变控制流的语句,因此goto
或return
应该可以工作。有关详细信息,请参阅 MSDN:http://msdn.microsoft。 com/en-us/library/06tc147t(VS.71).aspx
You do not need to specifically use a
break
statement just one that changes the flow of control, so agoto
or areturn
should work.See MSDN for more info: http://msdn.microsoft.com/en-us/library/06tc147t(VS.71).aspx