如何消除"使用未分配的局部变量"

时间:2016-01-25 03:26:45

标签: c# if-statement

我正在编程c#并且我遇到了使用未分配变量的错误,我已经声明了变量。请帮忙。我甚至在visual studio 2010中完成了构建解决方案。

    public decimal FinishCost 
     {
        get {
            decimal fnCost;

            if (exteriorFinishChosen == ExteriorFinish.None) 
            {
                fnCost = Finish.None;
            }

            else if (exteriorFinishChosen == ExteriorFinish.Standard)
            {
                fnCost = Finish.Standard;
            }
            else if (exteriorFinishChosen == ExteriorFinish.Pearlized)
            {
                fnCost = Finish.Pearlized;
            }
            else if (exteriorFinishChosen == ExteriorFinish.Custom)
            {
                fnCost = Finish.Custom;
            }
            return fnCost;
        }
    }

1 个答案:

答案 0 :(得分:3)

您需要为fnCost提供初始值,即使该值为NULL0

public decimal FinishCost 
{
    get 
    {
        decimal fnCost = 0;

        if (exteriorFinishChosen == ExteriorFinish.None) 
        {
            fnCost = Finish.None;
        }

        else if (exteriorFinishChosen == ExteriorFinish.Standard)
        {
            fnCost = Finish.Standard;
        }
        else if (exteriorFinishChosen == ExteriorFinish.Pearlized)
        {
            fnCost = Finish.Pearlized;
        }
        else if (exteriorFinishChosen == ExteriorFinish.Custom)
        {
            fnCost = Finish.Custom;
        }
        return fnCost;
    }
}