当我尝试将字符串转换为int时,为什么TryParse()不起作用?

时间:2019-04-27 05:32:59

标签: c# structure tryparse

我是一个初学者,我有一个涉及结构的作业,我也在使用Visual Studio 2017。

我创建了一个结构,现在我试图将来自文本框的输入分配给所创建结构的实例的字段。我正在尝试将文本框中的字符串分配给我创建的结构中的int数据类型的字段。

当我尝试使用TryParse()方法从文本框中转换字符串时,它不起作用。 VS告诉我,在当前上下文中不存在名称“ varName”。这是什么意思?我该如何解决这个问题?

     enum Month
        {
            January, February, March, April, May, June, July, August, September, October, November, December
        }

        struct Person
        {
            public string name;

            public string jobTitle;

            public Month month;

            public int day;

            public int year;
        }

        private void submitButton_Click(object sender, EventArgs e)
        {

            Month month = (Month)Enum.Parse(typeof(Month), monthDropDown.Text);
            Person user;

            user.name = nameTextBox.Text;
            user.jobTitle = jobTitleTextBox.Text;
            user.month = month;
            user.day = int.TryParse(dayTxtBox.Text, out day); //here I'm trying to use the TryParse method but it gives me the error the name 'day' doesn't exist in the current context
            user.year = int.TryParse(yearTextBox.Text, out year); //here I'm trying to use the TryParse method but it gives me the error the name 'year' doesn't exist in the current context
        }

3 个答案:

答案 0 :(得分:3)

int.TryParse方法尝试将字符串解析为int。它可能会失败。因此它 not 不会返回int。它返回一个bool来表示解析实际上是否成功。因此,您需要为结果做好准备,以使其无法用作int

if(int.TryParse(dayTxtBox.Text, out var day))
{
    user.day = day;
}
else
{
    /// put code here to handle what should happen if user entered "hello" for example
}

或者,如果这是家庭作业,并且您的课程中尚未涵盖其中一些概念,则可以简化它,并假设用户从不犯错误,并且始终输入正确的数字(警告:不是现实生活中的情况) :

user.day = int.Parse(dayTxtBox.Text);

答案 1 :(得分:1)

您需要在out方法中声明要用作TryParse参数的变量

在您的情况下,您使用了out dayout year,但是您需要告诉编译器dayyear变量的类型是什么。

您可以使用三元运算符,如果您的输入成功解析,则它将解析后的值返回到user.dayuser.year,否则仅返回0。

user.day = int.TryParse(dayTxtBox.Text, out int day) ? day : 0;
user.year = int.TryParse(yearTextBox.Text, out int year) ? year : 0;

或更简单地使用if....else块,

if (int.TryParse(dayTxtBox.Text, out int day))
{
    user.day = day;
}
else
{
    user.day = 0; //Or set any value whatever you want when parsing fail
}

答案 2 :(得分:0)

我可以给您代码,但是最好的解决方案是使用不需要验证的控件。在TextBox中键入一天是1990年代。

最好是建议将日历控件绑定到DateTime theDate { get; set; }字段。