C# 无法将类型“string”隐式转换为“short”

C# 无法将类型“string”隐式转换为“short”,c#,C#,不断地得到错误 无法将typre“string”隐式转换为“short” 对于局部变量kundeID 警告相当冗长。您应该将kundeID解析为short或将kundeID更改为string protected void btnAdd_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(Request.QueryString["id"])) { string kunde

不断地得到错误

无法将typre“string”隐式转换为“short”


对于局部变量kundeID

警告相当冗长。您应该将kundeID解析为short或将kundeID更改为string

protected void btnAdd_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
    {       
        string kundeID = "-1";
        int id = Convert.ToInt32(Request.QueryString["id"]);
        int totalsum = Convert.ToInt32(ddlAmount.SelectedValue);

        Handlevogn handlevogn = new Handlevogn
        {
            TotalSum = totalsum,
            KundeID = kundeID,
            Dato = DateTime.Now,
            ErIHandlevogn = true,
            ProduktID = id
        };

        HandlevognModell modell = new HandlevognModell();
        lblResult.Text = modell.InsertHandlevogn(handlevogn);
    } 

最简单的解决方案是将kundelID改为short

然后,您之前在此处进行的隐式转换:

short kundelID = -1;
将是相同类型的短

另外,如果出于任何原因需要将kundelID转换为字符串,请在使用之前将其正确转换为kundelID

KundelID = kundelID; //this is called implicit because you implicitly tell kundelID, which is a short to be changed to KundelID, which is likely a short

然后,它也将是正确的。

您可以使用以下功能:

KundelID = Convert.ToInt16(kundelID);
谁将返回一个布尔值,如果函数可以强制转换,则返回true;如果函数不能强制转换,则返回false

您可以在以下情况下使用它:

Int16.TryParse(string value, out number);

若输出是对象转换为短,则can看起来是这样的

short id;
if(Int16.TryParse(Request.QueryString["id"], out id))
{
    ProduktID = id;
}
你可以用

short var_short = short.Parse(Convert.ToString(reader["something"]));
short var_short = short.Parse(Convert.ToString(reader["something"]));
short kundeID = -1;