c# - 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 设置为比较字符串的默认方式,而不是到处编写第一个代码示例?
解决方案
创建一个扩展方法(它可以使用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.
}
推荐阅读
- python - 在带有 sqlalchemy 的嵌套 sqlite3 查询中使用 ROW_NUMBER() 会导致 sqlite3.OperationalError: near "(": 语法错误
- python - Scrapy、Splash 和 Connection 被对方拒绝:10061
- sockets - 套接字端口是否与常规端口相同
- python-3.x - Python使用List Comprehension替换字符串列表中的空字符串
- arrays - Mongodb find() 需要 1 秒
- javascript - 使用 HapiJS 的实验室上下文帮助程序会导致错误
- php - 访问页面时的 HTML 505 (PHP)
- c - 使用加法的阶乘
- python - 如何让程序根据命令自行重启
- angular - 一个组件获取新的服务实例而不是共享实例