[英]Is there a better way to code an if statement looking for a variable to match one of many?
我需要检查变量是否具有几个不同的值之一。 目前,我有这样的代码:
if (cName == "Products" || cName == "Packages" || cName == "Contents" || cName == "Packages")
..
if (cName == "Products" || cName == "Packages" || cName == "Contents")
..
etc
在我看来,这不是很干净。 有没有一种更简单的单线方式可以执行此检查? 我不需要重复cName的一些代码?
是。
switch (cName)
{
case "Products":
case "Packages":
case "Contents": // If cName is one of the above, execute code below
... // DO STUFF
break;
case "Some-other-value": // if cName is exactly Some-other-value, execute code below
.. // DO STUFF
break;
}
C#方式被认为是lambda方式 :
if( System.Array.Find( new string[]{ "Products", "Packages", "Contents" }, (s) => s == cName ) != null )
..
或者,或者:
using System.Linq;
..
if( new string[]{ "Products", "Packages", "Contents" }.Any( s => s == cName ) )
..
ICollection.Contains
(或Enumerable.Any
)可能值得研究...
var standardCategories = new [] { "Products", "Packages", "Contents" };
if (standardCategories.Contains(cName) || cName == "Fred") {
...
} else if (standardCategories.Contains(cName)) {
...
}
请注意,这确实会引入“额外开销”,fsvo -在大多数情况下,它只是无关紧要,但能够捍卫您的决定:)就我而言,我每天都使用整齐的代码,并且从未遇到过这种方法存在问题,但我也不是游戏开发人员。
(在这种情况下,我将使用嵌套的 if语句,因为谓词似乎可以修改;上面的代码只是用法的一个示例。请注意,我正在检查“ Fred”作为“ Packages”的用法...两次。)
快乐的编码。
您也可以看看扩展方法。
public static class StringExtensions
{
public static bool EqualsAny(this string s, params string[] args)
{
return args.Contains(s);
}
}
然后,您可以使用此ike:
string cName = "Products";
if (cName.EqualsAny("Products", "Packages", "Contents", "Packages"))
{
}
尝试
List<string> myMatchList = new List<string> { "Products", "Packages", "Contents" };
if ( myMatchList.Contains ( cName ) )
或“内联版本”(请注意,它不具有内存/ CPU效率)
if ( (new List<string> { "Products", "Packages", "Contents" }).Contains ( cName ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.