首页 > 解决方案 > C#string.Equals如何设置默认的StringComparison?

问题描述

在我们的代码库中,我们有以下 311 个案例:

string.Equals(stringA, stringB, StringComparison.CurrentCultureIgnoreCase);

使用StringComparison.CurrentCultureIgnoreCase占所有string.Equals参考文献的 99%。

我不能覆盖其中任何一个,因为System.String它是一个密封类。

public static bool Equals(string a, string b)
public static bool Equals(string a, string b, StringComparison comparisonType)

是这里创建新静态实现的唯一选择,例如:

public static class StringComparer
{
  public static bool Equals(string a, string b)
  {
     return string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);
  }
}

有没有办法将 CurrentCultureIgnoreCase 设置为比较字符串的默认方式,而不是到处编写第​​一个代码示例?

标签: c#

解决方案


创建一个扩展方法(它可以使用null参数)。

为了简洁起见,我将其命名Eq(但保留它internal以免混淆代码的外部使用者)

internal static class StringExtensions
{
    /// <summary>Performs a <see cref="StringComparison.CurrentCultureIgnoreCase"><c>CurrentCultureIgnoreCase</c></see> equality check.</summary>
    public static Boolean Eq( this String x, String y )
    {
        return String.Equals( x, y, StringComparison.CurrentCultureIgnoreCase );
    } 
}

像这样使用:

if( stringX.Eq( stringY ) ) {

} 

扩展方法也可以在null不抛出 a 的情况下使用值NullReferenceException

String x = null;
String y = null;
if( x.Eq( y ) )
{
    // this will run without exceptions
}

对于具有可空引用类型的 C# 8.0+ 及更高版本,您可以使用属性改进方法,例如:

using System.Diagnostics.CodeAnalysis;

internal static class StringExtensions
{
    /// <summary>Performs a <see cref="StringComparison.CurrentCultureIgnoreCase"><c>CurrentCultureIgnoreCase</c></see> equality check.</summary>
    [returns: NotNullIfNotNull("x")]
    public static Boolean? Eq(
        this String? x,
        String? y
    )
    {
        if( x is null ) return null;
        return String.Equals( x, y, StringComparison.CurrentCultureIgnoreCase );
    } 
}

或者:

using System.Diagnostics.CodeAnalysis;

internal static class StringExtensions
{
    /// <summary>Performs a <see cref="StringComparison.CurrentCultureIgnoreCase"><c>CurrentCultureIgnoreCase</c></see> equality check. Always returns false when <param ref="x"/> is null.</summary>
    public static Boolean Eq(
        [NotNullWhen(true)] this String? x,
        [NotNullWhen(true)] String? y
    )
    {
        if( x is null ) return false;
        return String.Equals( x, y, StringComparison.CurrentCultureIgnoreCase );
    } 
}

这样编译器就可以使用这个Eq方法来确定null-state x(假设你对 没问题null.Eq( null ) == false就像在 SQL 中一样):

String? x = "foo" // or `null`;
String? y = "bar" // or `null`;
if( x.Eq( y ) )
{
    SomeMethodThatRequiresNonNullArgs( x ); // the compiler knows `x` and `y` are non-null here. 
}

推荐阅读