我有以下代码:
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 这样的关键字是方法签名的一部分吗?
最佳答案
out parameter modifier (C# Reference)
Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument.
另见:ref (C# Reference )
Members of a class can't have signatures that differ only by ref and out. A compiler error occurs if the only difference between two members of a type is that one of them has a ref parameter and the other has an out parameter.
关于c# - 使用值和引用参数类型重载的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19729895/