或者在带有字符串的C#中? [英] Or in C# with a string?

查看:68
本文介绍了或者在带有字符串的C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个新手问题:

如果我想说的话如下:



如果(狗!=猫或牛)
{
Console.WriteLine(狗不等于牛也不是猫!);
}



由于我使用字符串,因此无法使用'II'。



< b>我尝试了什么:



我尝试了II但是因为我有一个字符串它不起作用

解决方案

你不得不说:

  if (dog!=   cat&& dog!=   cow



  if (!(dog ==   cat || dog = =   cow))


< blockquote>如果你需要经常这样做,特别是如果不仅仅是几件物品那么你应该做一个这样的功能:

  public   static   bool  IsOneOf( string  s, params   string  [] many)
{
if (很多== null
throw new ArgumentNullException( many) ;
return ((IList< string>)many).Contains(s);
}

您可以使用它:

  if (!IsOneOf(dog,  cat  cow))
{
Console.WriteLine( 狗不等于牛也不是猫!);
}

这是非常基本的。

更高级的解决方案是制作通用的扩展方法:

  public   static   class  MyExtensionMethods 
{
public static bool IsOneOf< T>( this T s, params T [] many)
{
如果(很多== null
throw new ArgumentNullException( 许多);
return ((IList< T>)many).Contains(s);
}
}

您可以使用它:

  if (!dog.IsOneOf(  cat  cow))
{
Console.WriteLine( 狗不等于牛也不是猫!);
}

还有其他方法可以做到这一点,有些方法针对某些情况进行了优化。


So I have quite a newbie question:
What if I want to say like:

if (dog != "cat" or "cow")
{
   Console.WriteLine("A dog is not equal to a cow nor a cat!");
}


And 'II' cannot be used since I am using strings.

What I have tried:

I tried the II but since I have a string it wouldn't work

解决方案

You would have to say:

if (dog != "cat" && dog != "cow")

Or

if (!(dog == "cat" || dog == "cow"))


If you're going to need to do this frequently, especially if there are more than just a couple of items then you should make a function that does this:

public static bool IsOneOf(string s, params string[] many)
{
  if (many == null)
    throw new ArgumentNullException("many");
  return ((IList<string>)many).Contains(s);
}

You would use it like:

if (!IsOneOf(dog, "cat", "cow"))
{
   Console.WriteLine("A dog is not equal to a cow nor a cat!");
}

This is pretty basic.
A more advanced solution would be to make a generic extension method:

public static class MyExtensionMethods
{
  public static bool IsOneOf<T>(this T s, params T[] many)
  {
    if (many == null)
      throw new ArgumentNullException("many");
    return ((IList<T>)many).Contains(s);
  }
}

You would use it like:

if (!dog.IsOneOf("cat", "cow"))
{
   Console.WriteLine("A dog is not equal to a cow nor a cat!");
}

There are other ways to do this, some optimized for certain cases.


这篇关于或者在带有字符串的C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆