开发者

C# in operator-overloading

开发者 https://www.devze.com 2022-12-10 00:27 出处:网络
I just had an idea last nigth when writing an if-expression and sometimes the expression tend to be long when you have it like this:

I just had an idea last nigth when writing an if-expression and sometimes the expression tend to be long when you have it like this:

if(x == 1 || x == 2 || x == 33 || x == 4 || x == -5 || x == 61) { ... }

x can be enums,strings,ints,chars you get the picture.

I want to know if there are an easier way of writing this. I think of sql's operator 'in' for example as a eay to shorten the expression:

if(x in (1,2,33,4,-5,61)) { ... }

I know you can't write an expression like this with 'in' because the lexer and parser of the compiler won't recognize it.

Perhaps other solutions as extension methods of different types of x is the solution? In the coming .NET 4.0 i heard something about parameterized methods, should that solve the n amount of parameters supplied to the if-expression ?

Perhaps you un开发者_Go百科derstand me, have you an idea of a good practice/solution to this question?

/Daniel


I usually write an Extension Method as follows:

public static bool In<T>(this T source, params T[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}

Which can be used like this:

if(x.In(1,6,9,11))
{
      // do something....
}


Try the following

if ( (new []{1,2,33,4,-5,61}).Any(i => x == i) ) {
  ...
}


    public static bool In<T>(this T X, params T[] list)
    {
        foreach (var item in list)
        {
            if (X.Equals(item))
                return true;
        }
        return false;
    }


   string[] possible = new string[3] { 1, 2, 3);

   if (possible.Contains(x)) { ...


    bool In<T>(T num, params int args)
    {
        return (new List<T>(args)).Contains(num);
    }


Given that x is an int you could write an extension method like so:

public static bool In(this int i, params int[] values){
    foreach(int v in values) {
        if (i == v) {
            return true;
        }
    }
    return false;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消