CA1309:使用按顺序的 StringComparisonCA1309: Use ordinal StringComparison

Value
规则 IDRule ID CA1309CA1309
类别Category 全球化Globalization
修复是中断或非中断Fix is breaking or non-breaking 不间断Non-breaking

原因Cause

Nonlinguistic 的字符串比较运算不会将 StringComparison 参数设置为 Ordinalstringcomparison.ordinalignorecaseA string comparison operation that is nonlinguistic does not set the StringComparison parameter to either Ordinal or OrdinalIgnoreCase.

规则说明Rule description

许多字符串操作(最重要的是 System.String.CompareSystem.String.Equals 方法)现在提供接受 System.StringComparison 枚举值作为参数的重载。Many string operations, most importantly the System.String.Compare and System.String.Equals methods, now provide an overload that accepts a System.StringComparison enumeration value as a parameter.

指定 StringComparisonStringComparison 时,字符串比较是非语义的。When you specify either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, the string comparison is non-linguistic. 也就是说,在进行比较决策时,将忽略特定于自然语言的功能。That is, the features that are specific to the natural language are ignored when comparison decisions are made. 忽略自然语言功能意味着决策基于简单的字节比较,而不是按区域性参数化的大小写或相等表。Ignoring natural language features means the decisions are based on simple byte comparisons and not on casing or equivalence tables that are parameterized by culture. 因此,通过将参数显式设置为 StringComparisonStringComparison,你的代码通常会获得速度、提高正确性,并变得更可靠。As a result, by explicitly setting the parameter to either the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, increases correctness, and becomes more reliable.

如何解决冲突How to fix violations

若要修复与此规则的冲突,请将字符串比较方法更改为接受 System.StringComparison 枚举作为参数的重载,并指定 序数stringcomparison.ordinalignorecaseTo fix a violation of this rule, change the string comparison method to an overload that accepts the System.StringComparison enumeration as a parameter, and specify either Ordinal or OrdinalIgnoreCase. 例如,将 String.Compare(str1, str2) 更改为 String.Compare(str1, str2, StringComparison.Ordinal)For example, change String.Compare(str1, str2) to String.Compare(str1, str2, StringComparison.Ordinal).

何时禁止显示警告When to suppress warnings

如果库或应用程序适用于受限制的本地受众,或应使用当前区域性的语义,则可以安全地禁止显示此规则发出的警告。It is safe to suppress a warning from this rule when the library or application is intended for a limited local audience, or when the semantics of the current culture should be used.

请参阅See also