代码之家  ›  专栏  ›  技术社区  ›  Cheung

C#可空类型问题[重复]

c#
  •  0
  • Cheung  · 技术社区  · 16 年前


    Nullable types and the ternary operator. Why won’t this work?

    例如:

    int? taxid;
    if (ddlProductTax.SelectedValue == "") {
      taxid = null; } 
    else {
      taxid = Convert.ToInt32(ddlProductTax.SelectedValue);
    } //Correct
    

    但是

    int? taxid;
    taxid = (ddlProductTax.SelectedValue == "" ? null : Convert.ToInt32(ddlProductTax.SelectedValue)); //Error
    

    这个(?)?真部:假部);不缺少(if..else..)?

    5 回复  |  直到 9 年前
        1
  •  4
  •   Christian C. Salvadó    16 年前

    三元运算符的最后两个操作数应产生相同的类型。

    把两边抛向 int? :

    taxid = ddlProductTax.SelectedValue == "" ?
                                     (int?)null
                                     : Convert.ToInt32(ddlProductTax.SelectedValue); 
    

    您可以在规范中看到确切的行为:

        2
  •  1
  •   Community Mohan Dere    9 年前

    复制
    Nullable types and the ternary operator: why is `? 10 : null` forbidden?

    解决方法如下:

    string x = "";
    int? taxid;
    taxid = (x == "" ? null : (int?) Convert.ToInt32(x)); // add the int? cast
    Console.WriteLine(taxid);
    
        3
  •  0
  •   this. __curious_geek    16 年前

    int? taxid; 
    taxid = (ddlProductTax.SelectedValue == "" ? null : new int?(Convert.ToInt32(ddlProductTax.SelectedValue))); //Now it works.
    
        4
  •  0
  •   hakan    16 年前

    这里有一个小助手方法

    taxid = GetNullableInt32(ddlProductTax.SelectedValue);
    
    public static int? GetNullableInt32(string str)
    {
            int result;
            if (Int32.TryParse(str, out result))
            {
                return result;
            }
            return null;
    }
    
        5
  •  0
  •   ChrisBD    16 年前

    我认为这取决于表达式的求值方式。 与 ? : null 价值与价值 Int32

    尝试:

    taxid = (ddlProductTax.SelectedValue == "" )? Convert.ToInt32(null) : Convert.ToInt32(ddlProductTax.SelectedValue);