gpt4 book ai didi

c# - 令人困惑的重载决议

转载 作者:行者123 更新时间:2023-11-30 15:24:56 27 4
gpt4 key购买 nike

我有一个类继承自另一个类以允许使用可空值。但是当我将它与不可空值一起使用时 ,它无论如何都会为可空值使用重载。

我不明白为什么在这段代码中类 c2 的功能屏蔽了类 c1 的功能:

class c1
{
public void fn1(int value)
{
Console.WriteLine("value {0} is normal", value);
}
public void fn1(int? value)
{
Console.WriteLine("value {0} is nullable", value);
}
public void fn2(int value)
{
Console.WriteLine("value {0} is normal", value);
}
}
class c2: c1
{
public void fn2(int? value)
{
Console.WriteLine("value {0} is nullable", value);
}
}

class Program
{
static void Main(string[] args)
{
c1 o1 = new c1();
c2 o2 = new c2();
int val = 10;
o1.fn1(val);
o2.fn1(val);
o2.fn2(val);
Console.ReadLine();
}
}

结果是:

value 10 is normal.
value 10 is normal.
value 10 is nullable.

但是 c2 有函数 fn2(int)。

最佳答案

这是我在 Jon Skeet 的博客上找到的。

Inheritance can cause a confusing effect. When the compiler goes looking for instance method overloads, it considers the compile-time class of the "target" of the call, and looks at methods declared there. If it can't find anything suitable, it then looks at the parent class... then the grandparent class, etc. This means that if there are two methods at different levels of the hierarchy, the "deeper" one will be chosen first, even if it isn't a "better function member" for the call.

http://csharpindepth.com/Articles/General/Overloading.aspx

关于c# - 令人困惑的重载决议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32001371/

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