I do not understand and cannot find on the Internet why Derived.Foo (object) is being called?
, , . : int , , Base.Foo(int)
, -in-Derived , --, Derived.Foo(object)
.
: "this" , Foo(int)
Base
Foo(object)
Derived
. int , Derived to Base, .
# .
# , , , , . : , , , , .
, , (1) , , , , ! - (2) .
, ; , - " , ". , , - . , # , , , , .
. ; WordPress MSDN .
https://blogs.msdn.microsoft.com/ericlippert/2007/09/04/future-breaking-changes-part-three/
https://ericlippert.com/2013/12/23/closer-is-better/
, Derived.Foo(int)?
, :
: . (!)
public class Derived : Base
{
public new void Foo(int x)
{
Console.WriteLine("Derived.Foo(int)");
}
public void Foo(object o)
{
Console.WriteLine("Derived.Foo(object)");
}
}
Derived.Foo(int)
, . , , int, .
, , Foo
Base
. ! , , , .
: . ( !)
Derived d = new Derived();
int i = 1;
((Base)d).Foo(i);
Foo , . , , "gotcha". ; .
. Microsoft, , API " ". . https://blogs.msdn.microsoft.com/ericlippert/2008/09/08/high-maintenance/
, , . .
: ; . ()
, , Foo (int). ! Foo (object) .
public void Foo(object o)
{
if (o is int)
((Base)this).Foo((int)o));
else
Console.WriteLine("Derived.Foo(object)");
}
Foo (object), , Derived.Foo(object) , 100% - . ; , .
: , , . ()
, . ; . . .
:
, ,
public static void Bar(Action<object> a) { }
public static void Bar(Action<int> a) { }
:
Bar(d.Foo);
?
. , . !
: #, 2012 , Microsoft. Roslyn , , : https://github.com/dotnet/roslyn/issues/6560 p >
, # 5 , , 6, # 7. , # 7. Roslyn github
, . , , , , , # .
, # 5, , .
. #.
-, d.Foo
Action<object>
? . : object x = default(object); d.Foo(x)
, ? , , Derived.Foo(object)
. Bar(Action<object>)
.
-, d.Foo
Action<int>
? . , int x = default(int); d.Foo(x);
, ? , , Derived.Foo(object)
. Bar(Action<int>)
.
. Derived.Foo(object)
Action<int>
, ?
#; # 3. , , , . :
, E D , .
, #. ... .
. . ? № Action<int>
Action<object>
, . , .
- , , - , , , Bar(Action<object>)
, Bar(Action<int>)
, Bar(Action<object>)
. , , : , . ; , , . , # , " , , , , , , ". , " , " - JavaScript Visual Basic, #. # " , , ".
, , , .