有没有在C#中的任何方式来覆盖类的方法,扩展方法? [英] Is there any way in C# to override a class method with an extension method?

查看:104
本文介绍了有没有在C#中的任何方式来覆盖类的方法,扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有过几次在那里我会想覆盖类中的方法,扩展方法。有没有办法做到这一点在C#?

There have been occasions where I would want to override a method in a class with an extension method. Is there any way to do that in C#?

例如:

public static class StringExtension
{
    public static int GetHashCode(this string inStr)
    {
        return MyHash(inStr);
    }
}

在这里,我想这方面的一个例子是,能够为一个字符串的哈希存储到数据库中,并有相同的值由所有使用String类的哈希值(即词典等类中使用)由于内置的​​.Net散列算法不能保证是从框架到下一个版本兼容,我想用我自己来取代它。

A case where I've wanted to do this is to be able to store a hash of a string into a database and have that same value be used by all the classes that use the string class's hash (i.e. Dictionary, etc.) Since the built-in .Net hashing algorithm is not guaranteed to be compatible from one version of the Framework to the next, I want to replace it with my own.

有其他情况我碰到,我会想重写一个类方法,扩展方法以及因此它不只是特定的字符串类或GetHash code方法。

There are other case I've run into where I'd want to override a class method with an extension method as well so it's not just specific to the string class or the GetHashCode method.

我知道我可以与继承了现有的类做到这一点,但它会很方便,能够在很多情况下,一个扩展做到这一点。

I know I could do this with subclassing off an existing class but it would be handy to be able to do it with an extension in a lot of cases.

推荐答案

没有;扩展方法从来没有一个合适的签名优先级高于一个实例方法,从不参与多态性( GetHash code 虚拟法)。

No; an extension method never takes priority over an instance method with a suitable signature, and never participates in polymorphism (GetHashCode is a virtual method).

这篇关于有没有在C#中的任何方式来覆盖类的方法,扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆