关于C#:重写命名空间范围内的equals方法

Overriding Equals method at namespace scope

UseCase:在最近的代码修复中,我注意到,在字符串比较之前,开发人员没有统一地转换字符串的大小写,这导致了生产环境中的错误。

这使我需要在已经存在的代码的名称空间范围内重写默认的equals()方法,在这些代码中会进行数百个位置的字符串比较。

在我去400多个地方手工修理之前,我试着用这些方法,但没有找到满意的结果。

Approach1:
Problem: It requires new method name -> NewEquals(). This requires changes in all the classes.

We can't use 'Equals()' here as instance method takes higher precedence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Program
{
    static void Main(string[] args)
    {
        string strFromConfig ="sometext";
        const string str ="SomeText";

        Console.WriteLine(str.Equals(strFromConfig));   // False
        Console.WriteLine(str.NewEquals(strFromConfig));    // True
    }
}
static class StringCompare      // Extension method approach
{
    public static bool NewEquals(this string str, string strconfig)
    {
        // edited this as per the suggestion in the comments.
        return str.Equals(strconfig, StringComparison.OrdinalIgnoreCase);
    }        
}

Approach2:

Problem: Maybe I am making some mistake in overriding Equals().

Even if it works, it has one con that this overridden function won't
be available within the namespace. And hence it won't fix in all the classes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Program
{
    static void Main(string[] args)
    {
        string strFromConfig ="sometext";
        const string str ="SomeText";

        Console.WriteLine(str.Equals(strFromConfig));  // False

        // This also doesn't invoke overridden method.
        Console.WriteLine(str.Equals((object)strFromConfig));  // False
    }
    public override bool Equals(object obj)
    {   //  Program control doesn't enter here. So could not test the below two returns.
        return base.Equals(obj);
        //return base.ToString().ToLower().Equals(obj.ToString().ToLower());
    }
}

有人能帮我知道实现我想要的是可行的吗?>一个改变-许多修正。


如果您不想进行具有文化意识的比较,请使用

1
string.Equals(val1, val2, StringComparison.OrdinalIgnoreCase)

另外,在配置系统周围做一个包装,让所有类都使用这个包装来访问app/web.configs。这样地

1
2
3
4
5
6
7
8
9
public class Configuration: IConfiguration
{
   public Configuration
   {
     this.Foo = ConfigurationManager.AppSettings["MyConfig"];
   }
   public string Foo { get; private set; }
   public bool IsMatch(string str) { return string.Equals(str, this.Foo, StringComparison.OrdinalIgnoreCase); } }
}

然后,您可以将IConfiguration的实例注入到您在项目中使用的任何类构造函数中。

我强烈建议不要使任何超载相等。你想要的工具已经在BCL中了,所以为什么要重新发明轮子。做400多个替换可能会很痛苦,但是像resharper这样的工具可以帮助您,或者只是做一个简单的查找和替换。我想在生产之前检查任何代码更改。