在c#多变量switch语句 [英] Multi-variable switch statement in c#

查看:1292
本文介绍了在c#多变量switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个switch语句这需要几个变量,看起来是这样的:

I would like use a switch statement which takes several variables and looks like this:

switch (intVal1, strVal2, boolVal3)
{
   case 1, "hello", false:
      break;
   case 2, "world", false:
      break;
   case 2, "hello", false:

   etc ....
}

就我个人来说,这是不可能在C#纯,问题是:有任何3D党库它实现了这样的事情在一个不错的和有效的方法。 (我不希望使用的原因很明显嵌套switch语句)。

As far as I am concerned this is not possible in c# pure, the question is: is there any 3d party library which implements something like this in a nice and efficient way. (And I do not want to use nested switch statements for obvious reasons).

推荐答案

有没有内置的功能,要做到这一点在C#中,我不知道任何图书馆这样做。

There is no built-in functionality to do this in C#, and I don't know about any library to do this.

下面是另一种方法,使用元组和扩展方法:

Here is an alternative approach, using Tuple and extension methods:

using System;

static class CompareTuple {
    public static bool Compare<T1, T2, T3>(this Tuple<T1, T2, T3> value, T1 v1, T2 v2, T3 v3) {
        return value.Item1.Equals(v1) && value.Item2.Equals(v2) && value.Item3.Equals(v3); 
    }
}

class Program {
    static void Main(string[] args) {
        var t = new Tuple<int, int, bool>(1, 2, false);
        if (t.Compare(1, 1, false)) {
            // 1st case
        } else if (t.Compare(1, 2, false)) {
            // 2nd case
        } else { 
            // default
        }
    }
}

这基本上是做无非就是提供了一个方便的语法检查多个值 - 与使用开关的多个IFS而不是

This is basically doing nothing more than providing a convenient syntax to check for multiple values - and using multiple ifs instead of a switch.

这篇关于在c#多变量switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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