如何使用 ?字符串的关键字

时间:2010-06-20 05:23:27

标签: c# asp.net conditional conditional-operator

我有一个简单的条件,并希望用?:关键字实现它,但编译器不允许我。这是确切的样本

// in asp page decleration
<ajaxtoolkit:FilteredTextBoxExtender id="ftbeNumeric" runat="server" TargetControlID="textbox1" FilterType="Numbers" />
<asp:TextBox ID="textbox1" runat="server" />

// in code behind 
decimal x = textbox1.Text != string.IsNullOrEmpty ? Convert.ToDecimal(textbox1.Text) : 0;

我也试试这个

// in code behind 
decimal x = Convert.ToDecimal(textbox1.Text) != 0 ? Convert.ToDecimal(textbox1.Text) : 0;

这些样本的表面有错误。

如何使用?:关键字定义此内容?并注意textbox。text`可能为空。

3 个答案:

答案 0 :(得分:6)

考虑将其更改为

decimal x;
if (!decimal.TryParse(textbox1.Text, out x))
{
    // throw an exception?
    // set it to some default value?
}

当然,如果你想在无效/缺失的输入上抛出异常,你可以简单地使用.Parse方法,它会为你抛出一个。但是使用.TryParse可以让你自定义异常的消息,或者只是以另一种方式处理它,比如重新命名用户。

答案 1 :(得分:3)

String.IsNullOrEmpty是一种方法,而不是字段。正确的用法是String.IsNullOrEmpty(textbox1.Text)

答案 2 :(得分:0)

我用这句话修正了

string.IsNullOrEmpty(textbox1.Text) ? 0 : Convert.ToDecimal(textbox1.Text);
相关问题