我有以下代码:
class Calculator
{
public int Sum(int x, int y)
{
return x + y;
}
public int Sum(out int x, out int y)
{
x = y = 10;
return x + y;
}
}
class Program
{
static void Main(string[] args)
{
int x = 10, y = 20;
Calculator calculator = new Calculator();
Console.WriteLine ( calculator.Sum ( x , y ) );
Console.WriteLine ( calculator.Sum ( out x , out y ) );
}
}
尽管方法签名仅与out
关键字不同,但此代码运行良好。
但是以下代码不起作用:
class Calculator
{
public int Sum(ref int x, ref int y)
{
return x + y;
}
public int Sum(out int x, out int y)
{
x = y = 10;
return x + y;
}
}
class Program
{
static void Main(string[] args)
{
int x = 10, y = 20;
Calculator calculator = new Calculator();
Console.WriteLine ( calculator.Sum ( ref x , ref y ) );
Console.WriteLine ( calculator.Sum ( out x , out y ) );
}
}
为什么这段代码不起作用?像 ref 和 out 这样的关键字是方法签名的一部分吗?