C# 有没有办法简化C语言中的多个| |逻辑运算符?
是否有现成的解决方案来简化此过程:C# 有没有办法简化C语言中的多个| |逻辑运算符?,c#,.net-core,C#,.net Core,是否有现成的解决方案来简化此过程: if(Someresult.innerObject.AnotherObject.Property == "1"|| Someresult.innerObject.AnotherObject.Property == "4") { } 这一行只有两个测试,如果它是6,代码将是可怕的 我想要这样的东西: if(Someresult.innerObject.AnotherObject.Property.IsOneOf("1", "4")){ } C中是否有类似于
if(Someresult.innerObject.AnotherObject.Property == "1"|| Someresult.innerObject.AnotherObject.Property == "4") {
}
这一行只有两个测试,如果它是6,代码将是可怕的
我想要这样的东西:
if(Someresult.innerObject.AnotherObject.Property.IsOneOf("1", "4")){
}
C中是否有类似于此的现成解决方案?是的,您可以,
你必须使用这些从
使用System.Linq
名称空间
string[] stringArray = { "1", "4" };
if(stringArray.Any(Someresult.innerObject.AnotherObject.Property))
你的标题是关于&,你的问题主体是关于| |。你是说哪一个?这不是编译。现在,如果您将
Any
更改为Contains
,那将是另一回事。另外,if(新字符串[]{“1”,“4”}.Contains(Someresult.innerObject.AnotherObject.Property)){..}
是一个有效的选项将此类添加到您的项目中,然后调用所需的方法,即静态类扩展方法{public static bool IsOneOf(this T item,params T[]items){if(items==null)抛出新ArgumentNullException(“items”);返回items.Contains(item);}}我创建了一个扩展方法…“IsOneOf”关于String类,它做得非常棒。我认为,这是我们在C#中的最佳选择。我对extesion方法有点偏见,因为它似乎改变了框架,但事实并非如此。如果Microsoft创建的方法过于具体,文档将比现在更令人厌烦。