【问题标题】:C# Error: Cannot implicitly convert type 'int' to 'short' for item valueC# 错误:无法将项目值的类型“int”隐式转换为“short”
【发布时间】:2011-07-05 06:41:07
【问题描述】:

我正在学习 C#,但一直收到错误消息“无法将类型 'int' 隐式转换为 'short'”。

在我的数据库所在的 Microsoft SQL Server 中,U_Weeks_In_Month 被定义为 smallint。我需要做什么来解决这个错误?

我尝试像在年份文本字段中一样使用 short.Parse,但这不适用于该项目,即

U_Weeks_In_Month = short.Parse(item.WeekNumber),

有什么办法吗?

我的代码是:

var weekInfos = SAPUtility.GetWeekInfo(dateTimePicker1.Value, 52);

// Create object
foreach (var item in weekInfos)
{
    // Get new code
    var newWeeklyCode = weeklyPeriodService.GenerateSAPCode();

    var weeklyPeriodAdd =
        new WeeklyPeriod
        {
            Code = newWeeklyCode,
            Name = newWeeklyCode,
            U_Tax_Year = short.Parse(txt_tax_year.Text),
            U_Month = item.Month.ToString(),
            U_Pay_Process_Status = "N",
            U_Payroll_Year = short.Parse(txt_tax_year.Text),
            U_Weeks_In_Month = item.WeekNumber,
            U_Starting_date = item.FirstDayOfWeek,
            U_Ending_date = item.LastDayOfWeek,
        };

    // Save record
    weeklyPeriodService.AddWeeklyPeriod(weeklyPeriodAdd);
}

【问题讨论】:

  • 你能提供你班级的代码吗?你的字段是什么类型的?

标签: c# visual-studio-2010


【解决方案1】:

我怀疑你只需要:

U_Weeks_In_Month = (short) item.WeekNumber

另一种方法是将您的 WeekNumber 属性更改为 short 开始。

另外,我会将txt_tax_year.Text 的解析拉到循环之外:

short taxYear = short.Parse(txt_tax_year.Text);
foreach (var item in weekInfos)
{
    // Use taxYear in here
}

【讨论】:

    【解决方案2】:

    您可以投射项目,例如: U_Weeks_In_Month = (short)item.WeekNumber,

    但我会检查为什么 item.WeekNumber 是一个整数并更正它(假设代码是你的)。

    【讨论】:

      【解决方案3】:

      似乎item.WeekNumber 的类型是int。在这种情况下,编译器给出了正确的错误。如果您不确定解析是否成功,您应该使用short.Parse 或short.TryParse。

      【讨论】:

        猜你喜欢
        • 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
        相关资源
        最近更新 更多