简体   繁体   English

C# 错误:无法将项目值的类型“int”隐式转换为“short”

[英]C# Error: Cannot implicitly convert type 'int' to 'short' for item value

I am learning C# and keep getting an error "Cannot implicitly convert type 'int' to 'short'".我正在学习 C# 并不断收到错误“无法将类型'int'隐式转换为'short'”。

In Microsoft SQL Server where my database is, U_Weeks_In_Month is defined as smallint.在我的数据库所在的 Microsoft SQL 服务器中,U_Weeks_In_Month 定义为 smallint。 What do I need to do to solve this error?我需要做什么来解决这个错误?

I tried to use short.Parse just like in the year textfields but this does not work for the item, ie我尝试使用 short.Parse 就像在年份文本字段中一样,但这不适用于该项目,即

U_Weeks_In_Month = short.Parse(item.WeekNumber),

Any solution?有什么解决办法吗?

My code is:我的代码是:

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

I suspect you just need:我怀疑你只需要:

U_Weeks_In_Month = (short) item.WeekNumber

An alternative is to change your WeekNumber property to short to start with.另一种方法是将您的WeekNumber属性更改为short开始。

Additionally, I'd pull the parsing of txt_tax_year.Text outside the loop:此外,我txt_tax_year.Text的解析拉到循环之外

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

You can cast the item eg: U_Weeks_In_Month = (short)item.WeekNumber,您可以投射项目,例如:U_Weeks_In_Month = (short)item.WeekNumber,

But I would check why item.WeekNumber is an integer and correct it (assuming the code is yours).但我会检查为什么 item.WeekNumber 是 integer 并更正它(假设代码是你的)。

It seems that item.WeekNumber is of type int .似乎item.WeekNumber的类型是int In that case compiler is giving the right error.在这种情况下,编译器给出了正确的错误。 You should be using short.Parse or short.TryParse if you not sure that parsing will succeed.如果您不确定解析是否会成功,您应该使用short.Parseshort.TryParse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM