【问题标题】:C#. I keep getting an error stating I have "use of an unassigned local variable 'fullname'" [duplicate]C#。我不断收到一条错误消息,指出我“使用了未分配的局部变量‘全名’”[重复]
【发布时间】:2017-04-23 16:31:06
【问题描述】:

//我必须创建一个程序来确定姓名是否以正确的格式写入,然后一旦它认为它正确,它将名字和姓氏分开。

public partial class nameFormatForm : Form
{
    public nameFormatForm()
    {
        InitializeComponent();
    }

    private bool IsValidFullName(string str)
    {
        bool letters;
        bool character;
        bool fullname;

        foreach (char ch in str)
        {
            if (char.IsLetter(ch) && str.Contains(", "))
            {
                fullname = true;
            }

            else
            {
                MessageBox.Show("Full name is not in the proper format");
            }
        }
        return fullname;
    }

    private void exitButton_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void clearScreenButton_Click(object sender, EventArgs e)
    {
        exitButton.Focus();
        displayFirstLabel.Text = "";
        displayLastLabel.Text = "";
        nameTextBox.Text = "";
    }

    private void formatNameButton_Click(object sender, EventArgs e)
    {
        clearScreenButton.Focus();
    }
}

【问题讨论】:

  • 给全名赋值一个初始值,即:bool fullname = false;

标签: c# visual-studio-2015


【解决方案1】:

永远记住这 3 条 C# 规则:

  1. 要使用变量,必须对其进行初始化。
  2. 使用默认值初始化字段成员
  3. 局部变量未使用默认值进行初始化。

您违反了规则 1:在初始化之前使用 fullname。以下程序将阐明这一点:

public class Program
{
    public static void Main()
    {
        // This is a local and NOT initialized
        int number;
        var person = new Person();
        Console.WriteLine(person.age); // This will work
        Console.WriteLine(number); // This will not work
        Console.Read();
    }
}

public class Person
{
    // This is a field so it will be initialized to the default of int which is zero
    public int age;
}

要解决您的问题,您需要初始化fullname

bool fullname = false;

我会将变量重命名为更易读的名称,例如isFullName

【讨论】:

    【解决方案2】:

    声明一个没有初始值的变量,然后在带有if 语句的方法中返回它,该语句不能确定该值没有任何意义。如果你想给return 赋值,你必须给fullname 赋值。

    先初始化这个变量:

    bool fullname = false;
    

    【讨论】:

      猜你喜欢
      • 2016-10-04
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 2020-08-08
      • 1970-01-01
      相关资源
      最近更新 更多