How can System.String be properly wrapped for case-insensitivy?

前端 未结 5 1695
谎友^
谎友^ 2021-01-12 07:05

This question is not about managing Windows pathnames; I used that only as a specific example of a case-insensitive string. (And I if I change the example now, a w

5条回答
  •  -上瘾入骨i
    2021-01-12 07:30

    A shorter and more lightweight approach might be to create an extension method:

    public static class StringExt
    {
        public static bool IsSamePathAs(this string @this, string other)
        {
            if (@this == null)
                return other == null;
    
            if (object.ReferenceEquals(@this, other))
                return true;
    
            // add other checks
            return @this.Equals(other, StringComparison.OrdinalIgnoreCase);
        }
    }
    

    This requires far less coding than creating a whole separate class, has no performance overhead (might even get inlined), no additional allocations, and also expresses the intent pretty clearly IMO:

    var arePathsEqual = @"c:\test.txt".IsSamePathAs(@"C:\TEST.txt");
    

提交回复
热议问题