Field is never assigned to and will always have its default value 0

夙愿已清 提交于 2021-02-10 05:19:07

问题


I get the following error in my code and I'm not sure why:

Warning - 'SummaryForm.m_difficulty' is never assigned to, and will always have its default value 0

Code

public partial class SummaryForm : Form
{
    // Declares variables with the values pulled from the 'MainForm'
    int iCorrectACount = MainForm.iCorrectACount;
    int iCurrentQIndex = MainForm.iCurrentQIndex;

    private Difficulty m_difficulty;

    public SummaryForm()
    {

        InitializeComponent();

        double modifier = 1.0;
        if (m_difficulty == Difficulty.Easy) { modifier = 1.0; }
        if (m_difficulty == Difficulty.Medium) { modifier = 1.5; }
        if (m_difficulty == Difficulty.Hard) { modifier = 2; }

        // Sets the labels using integer values
        lblCorrectNum.Text = iCorrectACount.ToString();
        lblWrongNum.Text = (iCurrentQIndex - iCorrectACount).ToString();
        lblScoreTotal.Text = (iCorrectACount * modifier).ToString();
    }

Maybe this has something to do with why lblScoreTotal.Text will not change to the value * modifier but will on another form?

The reason I asked this question here is because someone advised me to disable warning messages but I didn't think that was the appropriate solution?

Thanks.


回答1:


The compiler is entirely correct: nothing is going to change your m_difficulty field, as far as you've shown. What do you expect to set that value? Did you actually mean to set it to something based on MainForm as per iCorrectACount and iCurrentQIndex?

How do you expect it would ever be anything other than whatever (Difficulty) 0 evaluates as?

It's pretty dodgy to be pulling initial values from a statically-accessed instance of a form, too, IMO. It would be much better if the constructor accepted initial values from whatever was constructing it.




回答2:


m_difficulty is private, so it can't be accessed from outside your class, but you never assign it inside, so it will never change.

Therefore, it makes no real sense to compare it, as it will always be equal to 0.




回答3:


You should always initialize a variable after you declared it.

private Difficulty m_difficulty = new Difficulty();

Something like that.

So you prevent it to be null (in this case you would get an exception).

The warning just tells you this.




回答4:


It sounds to me like you're expecting m_difficulty to be bound to a dropdown selection on your user form. It is not. Even if it were, you would want to access the SelectedValue property instead of the object itself. Maybe this is what you're looking for.

Difficulty m_difficulty = (Difficulty)Enum.Parse(ddDifficulty.SelectedValue); 


来源:https://stackoverflow.com/questions/15435292/field-is-never-assigned-to-and-will-always-have-its-default-value-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!