【问题标题】:C# Error: Cannot implicitly convert type 'int' to 'short'C# 错误:无法将类型“int”隐式转换为“short”
【发布时间】:2011-06-20 05:32:36
【问题描述】:

我正在学习 C#,并且正在使用 Visual Studio 2010 来构建工资单程序。我收到一个错误“无法将类型 'int' 隐式转换为 'short'”。

我的代码是:

private void btn_add_Click(object sender, EventArgs e)
        {
            try
            {
                // Get service instance
                var employerPeriodService = Program.Kernel.Get<IEmployerPeriodService>();

                // Get new code
                var newCode = employerPeriodService.GenerateSAPCode();

                // Create object
                var employerPeriodAdd =
                    new EmployerPeriod
                    {
                        Code = newCode,
                        Name = newCode,
                        U_Tax_year = int.Parse(cb_tax_year.Text),
                        //U_Day_hrs = cb_number_hours.Text,
                        //U_Week_days = cb_number_days_week.Text,
                        //U_Week_hrs = txt_number_hours_week.Text,
                        //U_Month_days = cb_number_days_month.Text,
                        //U_Month_hrs = txt_number_hours_month.Text,
                        //U_Fortnight_days = cb_number_days_fortnight.Text,
                        //U_Fortnight_hrs = txt_number_hours_fortnight.Text,
                        //U_Weeks_in_month = cb_avg_weeks_month.Text,
                        //U_No_of_Fortnights = cb_avg_fortnights_month.Text,
                        U_Starting_period = Convert.ToDateTime(dateTimePicker1.Text),
                        U_Ending_period = Convert.ToDateTime(dateTimePicker2.Text)

                        //U_Comments = txt_comments.Text
                    };

                // Save record
                employerPeriodService.AddEmployerPeriod(employerPeriodAdd);

                MessageBox.Show("Employer Payroll Period Added Successfully. Intake Ref: " + newCode.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (RulesException ex)
            {
                MessageBox.Show(ex.GetErrorMessages(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

在我的数据库所在的 Microsoft SQL Server 中,U_Tax_year 被定义为 smallint。我需要做什么来解决这个错误。我是否将从组合框“cb_tax_year.Text”中获得的内容转换为 int 以及如何实现这一点。

任何帮助表示赞赏。

【问题讨论】:

  • 你试过用 short.Parse 代替 int.Parse 吗?

标签: c# visual-studio-2010


【解决方案1】:

我怀疑它就像改变这个一样简单:

U_Tax_year = int.Parse(cb_tax_year.Text),

到这里:

U_Tax_year = short.Parse(cb_tax_year.Text),

基本上,您应该检查 U_Tax_year 属性的类型,并确保正确解析文本,以便 = 符号的 RHS 的结果与属性类型的赋值兼容。

【讨论】:

  • 谢谢。我认为一个int是一个int,无论是short int还是long int。解决了。​​
【解决方案2】:

SQLServer 的 smallint 相当于 c# 的 short。所以试试short.Parse() 而不是int.Parse()

【讨论】:

    【解决方案3】:

    使用 short.Parse 而不是 int.Parse

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-18
      • 2012-11-10
      • 2017-02-27
      • 2017-10-05
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多