如何调用base.base.GetHashCode()等二级基类方法

usr*_*usr 29 c# inheritance

class A
{
    public override int GetHashCode()
    {
        return 1;
    }
}
class B : A
{
    public override int GetHashCode()
    {
        return ((object)this).GetHashCode();
    }
}

new B().GetHashCode()
Run Code Online (Sandbox Code Playgroud)

这会溢出堆栈.我怎么能叫Object.GetHashCode()B.GetHashCode()

编辑:B现在继承自A.

Mar*_*ell 20

(编辑 - 误读问题)

如果你想获得原始object.GetHashCode()版本; 你不能 - 至少,除非A通过以下方式提供:

protected int GetBaseHashCode() { return base.GetHashCode();}
Run Code Online (Sandbox Code Playgroud)

(并B打电话GetBaseHashCode()).

它溢出的原因GetHashCode是(显然)是虚拟的 - 如果你把它投射到它并不重要object; 它仍然从实际对象中最衍生的实现开始,即B.GetHashCode()(因此爆炸).

  • @LBushkin - 我也这么认为; 但是当我在不久前尝试它时(使用自定义IL和"call"而不是"callvirt"),CLI拒绝了它,说它可能会破坏运行时的稳定性(这是一个简单的例子). (3认同)

Iga*_*nik 14

您可以使用RuntimeHelpers.GetHashCode(object)获取对象的原始哈希码:

  class A
  {
    public override int GetHashCode()
    {
      Console.WriteLine("base hashcode is: " + base.GetHashCode());

      return 1;
    }
  }

  class Program
  {
    public static void Main(string[] args)
    {
      A a = new A();

      Console.WriteLine("A's hashcode: " + a.GetHashCode());

      Console.WriteLine("A's original hashcode: " + RuntimeHelpers.GetHashCode(a));
    }
  }
Run Code Online (Sandbox Code Playgroud)

这会产生以下结果:

base hashcode是:54267293
A的hashcode:1
A的原始哈希码:54267293

如果你看一下RuntimeHelpers.GetHashCode(object)Reflector,你会看到它调用内部静态方法object.InternalGetHashCode(object).如果您想了解更多信息,请查看有关GetHashCode默认实现的此问题.


Sau*_*eil 7

我正在使用外部库,我也想调用base.base(因为某些情况下的bug).经过一些研究后,我遇到了这个页面http://www.rsdn.ru/forum/dotnet/475911.aspx

这很简单:使用要调用方法的基类定义委托,并将对象指针设置为*this(或您想要的对象)

所以,重要的代码是:

public delegate void MD();

public void Test() {
        // A is the base class you want to call the method.
        A a = new A();
        // Create your delegate using the method name "M" with the instance 'a' of the base class
        MD am = (MD)Delegate.CreateDelegate(typeof(MD), a, "M");
        // Get the target of the delegate and set it to your object (this in most case)
        am.GetType().BaseType.BaseType.GetField("_target", BindingFlags.Instance BindingFlags.NonPublic).SetValue(am, this);
        // call the method using the delegate.
        am();
    }
Run Code Online (Sandbox Code Playgroud)