gpt4 book ai didi

c# - 派生方法比 C# 中的覆盖更强大?

转载 作者:太空狗 更新时间:2023-10-30 00:15:51 25 4
gpt4 key购买 nike

(又是一个恼人的问题...)

询问this 之前-(这部分与我的问题有关)-我得到了答案:

See §7.6.5.1 of the C# 4 spec:

The set of candidate methods is reduced to contain only methods from the most derived types: For each method C.F in the set, where C is the type in which the method F is declared, all methods declared in a base type of C are removed from the set.

好的。

我有这段代码://.Dump() 就像一个 WriteLine 命令...

 public class Base
{
public void Foo(string strings) { "1".Dump();}
public virtual void Foo(object strings) { "2".Dump();}
}

public class Child : Base
{

public override void Foo(object strings) { "4".Dump();}
}

但是这段代码:

Child c = new Child();
c.Foo("d");

发出:“1”

但是等等......

我们不是说 被简化为只包含来自大多数派生类型的方法: 吗?

child 有 1 个来自其父亲的函数 public void Foo(string strings) 和一个 NEARER 覆盖函数

那么他为什么选择它的基地功能呢?继承的函数是否比覆盖更近?

是否与运行时覆盖有关?

请帮忙。

编辑

这种情况呢?

public class Base
{
public virtual void Foo(int x) { "1".Dump();}
}

public class Child : Base
{
public override void Foo(int x) { "2".Dump();}
public void Foo(object x) { "3".Dump();}
}

void Main()
{
Child c = new Child();
c.Foo(6); //emits "3"
}

最佳答案

那是因为您的 child 拿走了一个物体。

public class Child : Base
{
public override void Foo(object strings) { "4".Dump();}
}

将其设为字符串,然后调用子节点。

public class Child : Base
{
public override void Foo(string strings) { "4".Dump();}
}

为什么会这样?

因为编译器发现 child 有 object 参数,所以它必须转换为 string 而在基类中它很容易作为字符串使用。

所以它调用了 base one。

虽然覆盖函数更接近于子类。但是这里的规则在 child 和基础上是不同的。 Child 有对象,base 有字符串。如果两者都有 object 或者都有 string.

是公平的

我在 Jon Skeet 的 C# in Depth Overloading Section 中读到了这个

关于c# - 派生方法比 C# 中的覆盖更强大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10780883/

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