Delegate的默认Constructor的小问题
C#中,delegate有默认的一个参数的Constructor,参数的类型为delegate指向的类型。如:
private delegate string someString();
private void button3_Click(object sender, System.EventArgs e)
{
int x=10;
someString st=new someString(x.ToString);
Console.WriteLine(st());
}
private void button3_Click(object sender, System.EventArgs e)
{
int x=10;
someString st=new someString(x.ToString);
Console.WriteLine(st());
}
会输出10;
如果将参数显式声明:
private delegate string someString(string ss);
private void button3_Click(object sender, System.EventArgs e)
{
int x=10;
someString st=new someString(x.ToString);
Console.WriteLine(st(x.ToString()));
}
private void button3_Click(object sender, System.EventArgs e)
{
int x=10;
someString st=new someString(x.ToString);
Console.WriteLine(st(x.ToString()));
}
或者
private delegate string someString(string ss);
private void button3_Click(object sender, System.EventArgs e)
{
int x=10;
someString st=new someString(x.ToString);
Console.WriteLine(st(10));
}
private void button3_Click(object sender, System.EventArgs e)
{
int x=10;
someString st=new someString(x.ToString);
Console.WriteLine(st(10));
}
原理应该没有发生变化,但是
结果为110,x的值改为100,那么得到1100,即为x*10+x,很奇怪吧?为什么呢?
或许找到原因了:
int x=10;
someString st=new someString(x.ToString);
Console.WriteLine(st(x.ToString()));
someString st=new someString(x.ToString);
Console.WriteLine(st(x.ToString()));
其中,st(x.ToString())等价于x.ToString(x.ToString());
即x.ToString("10"),把输出结果格式化了,导致得到了110