C# 中有什么方法可以用扩展方法覆盖类方法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/899539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 22:07:58  来源:igfitidea点击:

Is there any way in C# to override a class method with an extension method?

c#extension-methodsoverriding

提问by Phred Menyhert

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#?

有时我想用扩展方法覆盖类中的方法。有没有办法在 C# 中做到这一点?

For example:

例如:

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

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.

我想要这样做的一种情况是能够将字符串的哈希存储到数据库中,并且所有使用字符串类哈希的类(即字典等)都使用相同的值。内置的 .Net 哈希算法不能保证从一个版本的 Framework 到下一个版本兼容,我想用我自己的替换它。

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.

我还遇到过其他情况,我想用扩展方法覆盖类方法,因此它不仅特定于字符串类或 GetHashCode 方法。

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.

我知道我可以通过对现有类进行子类化来做到这一点,但是在很多情况下能够通过扩展来做到这一点会很方便。

采纳答案by Marc Gravell

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

不; 扩展方法永远不会优先于具有合适签名的实例方法,并且永远不会参与多态(GetHashCode是一个virtual方法)。

回答by Chris Brandsma

If the method has a different signature, then it can be done -- so in your case: no.

如果该方法具有不同的签名,则可以完成 - 所以在您的情况下:不。

But otherwise you need to use inheritance to do what you are looking for.

但否则你需要使用继承来做你正在寻找的东西。

回答by Beatles1692

As far as I know the answer is no, because an extension method is not an instance.It's more like an intellisense facility to me that let you call a static method using an instance of a class. I think a solution to your problem can be an interceptor that intercepts the execution of a specific method (e.g. GetHashCode()) and do something else.To use such an interceptor (like the one Castle Project provides) all objects should be instansiated using an object factory (or an IoC container in Castle) so that thier interfaces can be intercepted through a dynamic proxy generated in runtime.(Caslte also lets you intercept virtual members of classes)

据我所知,答案是否定的,因为扩展方法不是实例。对我来说,它更像是一种智能感知工具,可以让您使用类的实例调用静态方法。我认为您的问题的解决方案可以是拦截器,它拦截特定方法的执行(例如 GetHashCode())并执行其他操作。要使用这样的拦截器(如 Castle Project 提供的拦截器),所有对象都应该使用对象工厂(或 Castle 中的 IoC 容器),以便可以通过运行时生成的动态代理拦截它们的接口。(Caslte 还允许您拦截类的虚拟成员)

回答by DanK

I have found a way to invoke an extension method with the same signature as a class method, however it does not seem very elegant. When playing around with extension methods I noticed some undocumented behavior. Sample code:

我找到了一种方法来调用具有与类方法相同的签名的扩展方法,但它似乎不太优雅。在使用扩展方法时,我注意到一些未记录的行为。示例代码:

public static class TestableExtensions
{
    public static string GetDesc(this ITestable ele)
    {
        return "Extension GetDesc";
    }

    public static void ValDesc(this ITestable ele, string choice)
    {
        if (choice == "ext def")
        {
            Console.WriteLine($"Base.Ext.Ext.GetDesc: {ele.GetDesc()}");
        }
        else if (choice == "ext base" && ele is BaseTest b)
        {
            Console.WriteLine($"Base.Ext.Base.GetDesc: {b.BaseFunc()}");
        }
    }

    public static string ExtFunc(this ITestable ele)
    {
        return ele.GetDesc();
    }

    public static void ExtAction(this ITestable ele, string choice)
    {
        ele.ValDesc(choice);
    }
}

public interface ITestable
{

}

public class BaseTest : ITestable
{
    public string GetDesc()
    {
        return "Base GetDesc";
    }

    public void ValDesc(string choice)
    {
        if (choice == "")
        {
            Console.WriteLine($"Base.GetDesc: {GetDesc()}");
        }
        else if (choice == "ext")
        {
            Console.WriteLine($"Base.Ext.GetDesc: {this.ExtFunc()}");
        }
        else
        {
            this.ExtAction(choice);
        }
    }

    public string BaseFunc()
    {
        return GetDesc();
    }
}

What I noticed was that if I called a second method from inside an extension method, it would call the extension method that matched the signature even if there was a class method that also matched the signature. For example in the code above, when I call ExtFunc(), which in turn calls ele.GetDesc(), I get the return string "Extension GetDesc" instead of the string "Base GetDesc" that we would expect.

我注意到如果我从扩展方法内部调用第二个方法,它会调用匹配签名的扩展方法,即使有一个类方法也匹配签名。例如在上面的代码中,当我调用 ExtFunc() 时,它又调用 ele.GetDesc(),我得到返回字符串“Extension GetDesc”而不是我们期望的字符串“Base GetDesc”。

Testing the code:

测试代码:

var bt = new BaseTest();
bt.ValDesc("");
//Output is Base.GetDesc: Base GetDesc
bt.ValDesc("ext");
//Output is Base.Ext.GetDesc: Extension GetDesc
bt.ValDesc("ext def");
//Output is Base.Ext.Ext.GetDesc: Extension GetDesc
bt.ValDesc("ext base");
//Output is Base.Ext.Base.GetDesc: Base GetDesc

This allows you to bounce back and forth between class methods and extension methods at will, but requires the addition of duplicate "pass-through" methods to get you into the "scope" you desire. I am calling it scope here for lack of a better word. Hopefully someone can let me know what it is actually called.

这允许您随意在类方法和扩展方法之间来回切换,但需要添加重复的“传递”方法才能进入您想要的“范围”。我在这里称它为范围是因为没有更好的词。希望有人可以让我知道它实际上叫什么。

You might have guessed by my "pass-through" method names that I also toyed with the idea of passing delegates to them in the hopes that a single method or two could act as a pass-through for multiple methods with the same signature. Unfortunately it was not to be as once the delegate was unpacked it always chose the class method over the extension method even from inside another extension method. "Scope" no longer mattered. I have not used Action and Func delegates very much though so maybe someone more experienced could figure that part out.

您可能已经从我的“传递”方法名称中猜到了,我还考虑过将委托传递给它们的想法,希望单个方法或两个方法可以充当具有相同签名的多个方法的传递。不幸的是,当委托被解压后,它总是选择类方法而不是扩展方法,即使是从另一个扩展方法内部也是如此。“范围”不再重要。不过,我并没有经常使用 Action 和 Func 委托,所以也许更有经验的人可以解决这个问题。