CA1307:为了清晰起见,请指定 StringComparisonCA1307: Specify StringComparison for clarity

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


字符串比较操作使用未设置参数的方法重载 StringComparisonA string comparison operation uses a method overload that does not set a StringComparison parameter.

规则说明Rule description

许多字符串比较操作提供接受 StringComparison 枚举值作为参数的重载。Many string compare operations provide an overload that accepts a StringComparison enumeration value as a parameter.

只要存在采用参数的重载 StringComparison ,就应该使用它而不是不采用此参数的重载。Whenever an overload exists that takes a StringComparison parameter, it should be used instead of an overload that does not take this parameter. 通过显式设置此参数,你的代码通常会更清晰且更易于维护。By explicitly setting this parameter, your code is often made clearer and easier to maintain. 有关详细信息,请参阅 显式指定字符串比较For more information, see Specifying string comparisons explicitly.


此规则不考虑 StringComparison 比较方法使用的默认值。This rule does not consider the default StringComparison value used by the comparison method. 因此,默认情况下使用字符串比较的方法和使用 Ordinal 此默认比较模式的用户可能会产生干扰。Hence, it can be potentially noisy for methods that use the Ordinal string comparison by default and the user intended to use this default compare mode. 如果只想要查看默认情况下使用特定于区域性的字符串比较的已知字符串方法的冲突,请改用 CA1310:指定 StringComparison 以保证正确性If you only want to see violations only for known string methods that use culture-specific string comparison by default, please use CA1310: Specify StringComparison for correctness instead.

如何解决冲突How to fix violations

若要修复与此规则的冲突,请将字符串比较方法更改为接受 StringComparison 枚举作为参数的重载。To fix a violation of this rule, change string comparison methods to overloads that accept the StringComparison enumeration as a parameter. 例如,将 str1.IndexOf(ch1) 更改为 str1.IndexOf(ch1, StringComparison.Ordinal)For example, change str1.IndexOf(ch1) to str1.IndexOf(ch1, StringComparison.Ordinal).

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

如果不需要意向清楚,则可以安全地禁止显示此规则发出的警告。It is safe to suppress a warning from this rule when clarity of intent is not required. 例如,测试代码或不可本地化的代码可能不需要它。For example, test code or non-localizable code may not require it.

请参阅See also