简体   繁体   English

C#在字符串类型上覆盖GetHashCode

[英]C# overriding GetHashCode on a string type

Is it possible to override the GetHashCode method for a string, int, int32 etc.. 是否可以为字符串,int,int32等覆盖GetHashCode方法。

I dont want to create a new object or class and override it that away. 我不想创建一个新的对象或类并覆盖它。 I wonder if there was a way to override the type's method. 我想知道是否有一种方法可以覆盖类型的方法。 Similar to an extension but not really. 与扩展类似,但并非如此。

string myString = "sometext";
myString.GetHashCode(); -- I want to override this method. 

No, you cannot. 你不能。 Even if you added an extension method, if there is an instance method and an extension method with the same signature being called then the instance method wins. 即使添加了扩展方法,如果存在实例方法和具有相同签名的扩展方法,则实例方法也将获胜。 You also can't extend string or int because they're sealed. 您也不能扩展stringint因为它们是密封的。 The best you'd be able to do is create an entirely new class/struct with a string/int property that overrides GetHashCode with your own implementation (you could provide implicit conversions to string or int as well if you wanted. 您能做的最好的事情是创建一个带有string / int属性的全新类/结构,该属性将使用您自己的实现覆盖GetHashCode(您也可以根据需要提供对stringint隐式转换。

I think you can only do it if it's in another class [http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in-c] 我认为,只有在其他课程中,您才能这样做[http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in -C]

Plus, I don't think you'd want to overwrite it globally because there is a strong likely hood that other things will be using that base GetHashCode() 另外,我认为您不希望在全球范围内覆盖它,因为很有可能其他事物将使用该基本GetHashCode()

Finally, ask yourself "Why do you want to do this?" 最后,问问自己“为什么要这样做?” If you don't have a really good reason, you don't need to do it. 如果您没有很好的理由,则不需要这样做。

If you do not want to create your own class, then no because an override is only possible within a subclass. 如果不想创建自己的类,则不要,因为只能在子类中进行覆盖。

An alternative would be to create a custom extension method like: 一种替代方法是创建一个自定义扩展方法,例如:

public static class MyExtensions
{
    public static int GetHashCode2(this string s)
    { 
         // Implementation
    }
}

This would have a similar effect, but you would need to call .GetHashCode2() rather than .GetHashCode() 这会产生类似的效果,但是您需要调用.GetHashCode2()而不是.GetHashCode()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM