Pattern matching - variable in scope outside if-block

前端 未结 2 1481
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-15 01:09

I\'m trying to understand why y is in scope in the following example:

static void Main(string[] args)
{
    int x = 1;
    if (x is int y) { }

         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-15 01:46

    The problem is the output code created, which results in this strange behavior, which is a bug in my opinion. I guess this will be fixed eventually.

    The thing is this: x is int y evaluates to true on compile time, resulting in the if rendered obsolete and the assignment done before the if. See the compiled code here:

    int num = 1;
    int num2 = num;
    bool flag = true;
    if (flag)
    {
    }
    Console.WriteLine("This should NOT be in scope:" + num2);
    

    There seems a bug in the compilation of the is object variant. It compiles to something like this (note the parenthesis I added):

    int num = 1;
    object arg;
    bool flag = (arg = num as object) != null;
    
    Console.WriteLine("This should NOT be in scope:" + arg);
    

    Which is valid, even in C# 6. However, the compiler thinks arg isn't always set. Adding an else branch fixes this bug:

    else { y = null; }
    

    Results in:

    int num = 1;
    object arg;
    bool flag = arg = num as object != null;
    if (!flag)
    {
        arg = null;
    }
    Console.WriteLine("This should NOT be in scope:" + arg);
    

提交回复
热议问题