如果string为null或为空,应该为string.Split(“;")返回什么 [英] what should be returned for string.Split(";") if string is null or empty
问题描述
如果字符串为空或空,
string.split(;")应该不会引发错误?
Shouldn't string.split(";") should throw an error ?
对我来说,我正在尝试这段代码,并且没有任何错误地通过它,
for me I am trying this code and goes through it without any error,
string a = string.empty;
if (a.Split(';').Length - 1 < 1)
谁能告诉我为什么它不会引发错误以及为什么if语句为真.
Can anyone tell me why it not throws an error and why if statement is true.
推荐答案
如果字符串为null,则 .Split()
将(显然)抛出 NullReferenceException
,例如任何其他实例方法.
If the string is null, .Split()
will (obviously) throw a NullReferenceException
, like any other instance method.
如果字符串为空,则 .Split()
将返回单个空字符串的数组(除非您传递 StringSplitOptions.RemoveEmptyEntries
).
这是其更普遍(且较少意外)行为的一个特例.如果分隔符没有出现在源字符串的任何地方,它将返回一个包含整个源字符串的数组.
If the string is empty, .Split()
will return an array of a single empty string (unless you pass StringSplitOptions.RemoveEmptyEntries
).
This is a corner case of its more general (and less unexpected) behavior; if the delimiter does not appear anywhere in the source string, it will return an array containing the entire source string.
这篇关于如果string为null或为空,应该为string.Split(“;")返回什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!