C#。我一直收到错误声明我已经使用了未分配的本地变量' fullname'"

时间:2017-04-23 16:31:07

标签: c# visual-studio-2015

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

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();
    }
}

2 个答案:

答案 0 :(得分:1)

永远记住C#的这三条规则:

  1. 要使用变量,必须对其进行初始化。
  2. 使用默认值
  3. 初始化字段成员
  4. 当地人未使用默认值进行初始化。
  5. 您违反规则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

答案 1 :(得分:0)

声明一个没有初始值的变量,然后在一个没有确定值的if语句的方法中返回它没有任何意义。如果您想要fullname其值,则必须为return分配值。

首先创建此变量:

bool fullname = false;