有人愿意解释这段代码如何产生以下输出吗?
using System;
namespace ConsoleApplication1
{
class Test
{
public override string ToString() { return "ToString override"; }
public string ToString(string optional = "")
{ return String.Format("ToString with optional parameter {0}", optional); }
}
class Test2
{
public new string ToString() { return "ToString new"; }
public string ToString(string optional = "")
{ return String.Format("ToString with optional parameter {0}", optional); }
}
class Program
{
static void Main(string[] args)
{
Test one = new Test();
Test2 two = new Test2();
Console.WriteLine(one);
Console.WriteLine(one.ToString());
Console.WriteLine(one.ToString("foo"));
Console.WriteLine("--");
Console.WriteLine(two);
Console.WriteLine(two.ToString());
Console.WriteLine(two.ToString("bar"));
Console.ReadKey();
}
}
}
ToString 覆盖
带有可选参数的 ToString
带有可选参数 foo 的 ToString
--
ConsoleApplication1.Test2
新的 ToString
带有可选参数 bar 的 ToString