忽略 null 语句,仅将方法应用于填充的字符串
如何忽略 null 语句,并仅应用一种方法来删除填充的字符串中的特殊字符。
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 为空,通过答案 1 的最佳方式是什么?
How do you ignore a null statement, and only apply a method to remove special characters to only strings that are populated.
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);
}
What's happening, is when the user presses and sends an answer one, and nothing for answer two I get an exception, because the method is trying to run on an empty string. What is the best way to pass answer1, if answer 2 is empty?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您的问题不在
RemoveSpecialChars
方法中,而是在SelectSingleNode
的返回值(可能是null
)或 < code>Attributes["keypress"] 属性(也可能为null
)。上述任何情况都会导致 NullReferenceException。下面是重写的代码,以防止第一个问题,这可能会导致问题:
更新:
要防止 null
keypress
属性,您可以对
执行相同的操作答案2。
It sounds like your problem is not in the
RemoveSpecialChars
method, but rather in the return value ofSelectSingleNode
(which may benull
) or theAttributes["keypress"]
attribute (which may also benull
).Any of the above will result in a
NullReferenceException
. Here's rewritten code to guard against the first, which is probably causing the issue:Update:
To guard against a null
keypress
attribute, you would doand the same for
Answer2
.