简体   繁体   English

如何避免使用永远不会发生的未分配变量?

[英]How to get around use of unassigned variable that can never happen?

In the following piece of code, the compiler gives a "Use of unassigned local variable" on 'intValue' on the return line.在下面的代码中,编译器在返回行的“intValue”上给出了“使用未分配的局部变量”。 However, there is no case where "intValue > 500" will be reached where it will be unassigned (because if intValue is unassigned, then valueIsInt is false, and the statement returns false before reaching intValue )但是,不会在未分配的情况下达到“intValue > 500”(因为如果未分配intValue ,则valueIsInt为 false,并且该语句在达到intValue之前返回 false)

Is there a way to get around this issue without modifying the logic or business logic of the code?有没有办法在不修改代码逻辑业务逻辑的情况下解决这个问题? This is a very simplified example;这是一个非常简化的例子; in a case where intValue is another type and the condition intValue > 500 is more complex, we can't simply give intValue a value in the else block like intValue = 0intValue是另一种类型并且条件intValue > 500更复杂的情况下,我们不能简单地在else块中给 intValue 一个值,例如intValue = 0

bool valueIsInt;

if (value is int intValue)
{
    valueIsInt = true;
}
else
{
    valueIsInt = false;
}

return valueIsInt && intValue > 500;

I want to avoid this in case the code in the else statement is more complex:我想避免这种情况,以防 else 语句中的代码更复杂:

else
{
    return false;
}

Such as this:比如这样:

bool valueIsInt;

if (value is int intValue)
{
    valueIsInt = true;
}
else
{
    if (value is string stringValue)
        valueIsInt = int.TryParse(stringValue, out intValue);
    else
        return false;
}

return valueIsInt && intValue > 500;

Updated更新

static bool IsValueGreaterThan500(object value)
{
    try
    {
        // Converts the value to int if it is not already an int
        // from bool, short, float, double, string, etc.
        return Convert.ToInt32(value) > 500;
    }
    catch
    {
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM