c# 7.0: switch on System.Type

后端 未结 9 1969
既然无缘
既然无缘 2020-12-03 04:10

No existing question has an answer to this question.

In c# 7, can I switch directly on a System.Type?

When I try:

    switch (Type)         


        
相关标签:
9条回答
  • 2020-12-03 04:50

    @toddmo suggested the following:

    switch (true)
    {
        case bool _ when extruder.Temperature < 200:
            HeatUpExtruder();
            break;
    
        // etc..
        default:
            StartPrintJob();
            break;
    }
    

    ...but why not go even further in his pursuit of simplicity. The following works just as well without needing the bool type qualification, nor the extraneous _ dummy variable:

    switch (true)
    {
        case true when extruder.Temperature < 200:
            HeatUpExtruder();
            break;
    
        // etc.
        default:
            StartPrintJob();
            break;
    }
    
    0 讨论(0)
  • 2020-12-03 04:52

    The (already linked) new pattern matching feature allows this.

    Ordinarily, you'd switch on a value:

    switch (this.value) {
      case int intValue:
        this.value = Math.Max(Math.Min(intValue, Maximum), Minimum);
        break;
      case decimal decimalValue:
        this.value = Math.Max(Math.Min(decimalValue, Maximum), Minimum);
        break;
    }
    

    But you can use it to switch on a type, if all you have is a type:

    switch (type) {
      case Type intType when intType == typeof(int):
      case Type decimalType when decimalType == typeof(decimal):
        this.value = Math.Max(Math.Min(this.value, Maximum), Minimum);
        break;
    }
    

    Note that this is not what the feature is intended for, it becomes less readable than a traditional if...else if...else if...else chain, and the traditional chain is what it compiles to anyway. I do not recommend using pattern matching like this.

    0 讨论(0)
  • 2020-12-03 05:03

    I found a simple and efficient way. It requires C# V7 to run. The switch("") means all cases will be satisfied up to the when clause. It uses the when clause to look at the type.

    List<Object> parameters = new List<object>(); // needed for new Action
    parameters = new List<object>
    {
        new Action(()=>parameters.Count.ToString()),
        (double) 3.14159,
        (int) 42,
        "M-String theory",
        new System.Text.StringBuilder("This is a stringBuilder"),
        null,
    };
    string parmStrings = string.Empty;
    int index = -1;
    foreach (object param in parameters)
    {
        index++;
        Type type = param?.GetType() ?? typeof(ArgumentNullException);
        switch ("")
        {
            case string anyName when type == typeof(Action):
                parmStrings = $"{parmStrings} {(param as Action).ToString()} ";
                break;
            case string egStringBuilder when type == typeof(System.Text.StringBuilder):
                parmStrings = $"{parmStrings} {(param as System.Text.StringBuilder)},";
                break;
            case string egInt when type == typeof(int):
                parmStrings = $"{parmStrings} {param.ToString()},";
                break;
            case string egDouble when type == typeof(double):
                parmStrings = $"{parmStrings} {param.ToString()},";
                break;
            case string egString when type == typeof(string):
                parmStrings = $"{parmStrings} {param},";
                break;
            case string egNull when type == typeof(ArgumentNullException):
                parmStrings  = $"{parmStrings} parameter[{index}] is null";
                break;
            default: throw new System.InvalidOperationException();
        };
    } 
    

    This leaves parmStrings containing...

    System.Action 3.14159, 42, M-String theory, This is a stringBuilder, parameter[5] is null

    0 讨论(0)
提交回复
热议问题