【问题标题】:Ignore a null statement, apply method only to strings that are populated忽略空语句,仅将方法应用于填充的字符串
【发布时间】:2011-06-20 19:08:47
【问题描述】:

如何忽略空语句,仅将删除特殊字符的方法应用于仅填充的字符串。

Answer1 = RemoveSpecialChars(doc.SelectSingleNode("/Main/Answer[@answerid='1']").Attributes["keypress"].Value);                 
Answer2 = RemoveSpecialChars(doc.SelectSingleNode("/Main/Answer[@answerid='2']").Attributes["keypress"].Value);

 public string RemoveSpecialChars(string input)
       {

           return Regex.Replace(input, @"[^0-9a-zA-Z\._]", string.Empty);
       }

发生的情况是,当用户按下并发送答案一,而答案二没有任何内容时,我得到一个异常,因为该方法试图在一个空字符串上运行。如果答案 2 为空,通过 answer1 的最佳方法是什么?

【问题讨论】:

    标签: c# string exception methods null


    【解决方案1】:

    听起来您的问题不在于RemoveSpecialChars 方法,而在于SelectSingleNode(可能是null)或Attributes["keypress"] 属性(也可能是null)的返回值.

    以上任何一项都将导致NullReferenceException。这是为了防止第一个问题而重写的代码,这可能是导致问题的原因:

    var node1 = doc.SelectSingleNode("/Main/Answer[@answerid='1']");
    var node2 = doc.SelectSingleNode("/Main/Answer[@answerid='2']");
    
    Answer1 = node1 == null ? null : RemoveSpecialChars(node1.Attributes["keypress"].Value);
    Answer2 = node2 == null ? null : RemoveSpecialChars(node2.Attributes["keypress"].Value);
    

    更新

    要防止出现空的keypress 属性,您可以这样做

    Answer1 = node1 == null || node1.Attributes["keypress"] == null
                ? null 
                : RemoveSpecialChars(node1.Attributes["keypress"].Value);
    

    Answer2 也是如此。

    【讨论】:

    • answerid 将一直存在,有时是空的按键。异常来自在空字符串上运行该方法,在本例中为 answerid2= 2,但 keypress2="",您建议的方式是否相同?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    相关资源
    最近更新 更多