在 C # 中有没有办法用扩展方法重写类方法?

在某些情况下,我希望用扩展方法重写类中的方法。在 C # 中有什么方法可以做到这一点吗?

例如:

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

我一直想这样做的一个例子是,能够将一个字符串的哈希值存储到数据库中,并让所有使用该字符串类的哈希值的类(例如 Dictionary 等)使用相同的值。NET 哈希算法不能保证从一个版本的框架兼容到下一个,我想用我自己的替换它。

在其他情况下,我也想用扩展方法覆盖类方法,这样它就不仅仅是特定于字符串类或 GetHashCode方法了。

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

36610 次浏览

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).

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.

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)

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.

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.