C# optional arguments in abstract method
Given:
interface IFoo
{
void Print(string text = "abc");
}
class Bar : IFoo
{
public void Print(string text = "def")
{
Console.WriteLine(text);
}
}
class Program
{
static void Main(string[] args)
{
Bar b = new Bar();
b.Print();
IFoo f = b as IFoo;
f.Print();
}
}
The output is:
def
abc
Is just me or this is a little odd? Initially I was expecting "def" in both cases.开发者_如何学运维 However, if that would be the case then the optional argument abstract methods would be useless. But still seems like a good starting point for nasty bugs.
Optional parameters are a compiler feature, and the compiler can only work on type information that's available at compile time. Therefore the values are taken from the type of the reference you're operating on, not the actual run-time type. In this simple test case it would be possible to find out the actual type of f
via static analysis, but that only rarely works in real-life examples and therefore isn't implemented.
精彩评论