gpt4 book ai didi

c# - C#中的多重继承问题

转载 作者:太空狗 更新时间:2023-10-29 22:05:25 25 4
gpt4 key购买 nike

This question came to my mind while I am reading the post Why doesn't C# support multiple inheritance? from MSDN Blog.

首先看下面的代码:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class A
{
int num;
public A()
{
num = 0;
}
public A(int x)
{
num = x;
}
public override int GetHashCode()
{
return num + base.GetHashCode();
}
}
class B : A
{
int num;
public B()
{
num = 0;
}
public B(int x)
{
num = x;
}
public override int GetHashCode()
{
return num + base.GetHashCode();
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
Console.Write(a.GetHashCode() + " " + b.GetHashCode());
Console.Read();
}
}
}

Object class is the ultimate base class of all classes .所以它是A的基类和 B在我的程序中也使 A作为 B 的基类.所以B现在有两个基类,一个是A另一个是 Object .我重写了一种方法 GetHashCode() Object Class在类里面AB两个都。但是在类里面B , base.GetHashCode()方法返回 GetHashCode() 的返回值类的方法A .但我想要这个值来自 Object class .我怎样才能得到它?

最佳答案

B 只有一个基类,即AA 有一个基类,即object。没有多重继承; object 仅由尚未从其他对象继承的类继承。

如果您仍然认为需要调用 object.GetHashCode(),在问题 How to invoke (non virtually) the original implementation of a virtual method? 中有一个非常 hacky 的解决方法来执行此操作.

关于c# - C#中的多重继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3425760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com