为什么这(空||的TryParse!)有条件的结果[使用未分配的局部变量"? [英] Why does this (null || !TryParse) conditional result in "use of unassigned local variable"?

查看:129
本文介绍了为什么这(空||的TryParse!)有条件的结果[使用未分配的局部变量"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code结果的使用未分配的局部变量numberOfGroups的:

The following code results in use of unassigned local variable "numberOfGroups":

int numberOfGroups;
if(options.NumberOfGroups == null || !int.TryParse(options.NumberOfGroups, out numberOfGroups))
{
    numberOfGroups = 10;
}

不过,这code正常工作(虽然 ReSharper的说, = 10 是多余的):

int numberOfGroups = 10;
if(options.NumberOfGroups == null || !int.TryParse(options.NumberOfGroups, out numberOfGroups))
{
    numberOfGroups = 10;
}

我缺少的东西,或者是不喜欢的编译器我的 ||

我已经缩小下来到动态引起的问题(选项在我的上面$动态变量C $ C)。现在的问题仍然存在,我为什么不能做到这一点

I've narrowed this down to dynamic causing the issues (options was a dynamic variable in my above code). The question still remains, why can't I do this?

这code的的编译:

internal class Program
{
    #region Static Methods

    private static void Main(string[] args)
    {
        dynamic myString = args[0];

        int myInt;
        if(myString == null || !int.TryParse(myString, out myInt))
        {
            myInt = 10;
        }

        Console.WriteLine(myInt);
    }

    #endregion
}

不过,这code的确实的:

internal class Program
{
    #region Static Methods

    private static void Main(string[] args)
    {
        var myString = args[0]; // var would be string

        int myInt;
        if(myString == null || !int.TryParse(myString, out myInt))
        {
            myInt = 10;
        }

        Console.WriteLine(myInt);
    }

    #endregion
}

我不知道动态能胜任这份工作的一个因素。

I didn't realize dynamic would be a factor in this.

推荐答案

我是pretty肯定这是一个编译器错误。 - 尼斯找到!

I am pretty sure this is a compiler bug. Nice find!

编辑:这是不是一个错误,因为Quartermeister证明;动态可能实现的一个奇怪的真正运营商这可能会导致永远不会被初始化。

it is not a bug, as Quartermeister demonstrates; dynamic might implement a weird true operator which might cause y to never be initialized.

下面是一个最小的摄制:

Here's a minimal repro:

class Program
{
    static bool M(out int x) 
    { 
        x = 123; 
        return true; 
    }
    static int N(dynamic d)
    {
        int y;
        if(d || M(out y))
            y = 10;
        return y; 
    }
}

我不明白为什么这应该是非法的;如果更换动态与布尔它编译就好了。

I see no reason why that should be illegal; if you replace dynamic with bool it compiles just fine.

我竟与C#队明天的会议;我会把它提到他们。道歉的错误!

I'm actually meeting with the C# team tomorrow; I'll mention it to them. Apologies for the error!

这篇关于为什么这(空||的TryParse!)有条件的结果[使用未分配的局部变量"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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