c# - 使用值和引用参数类型重载的方法

标签 c# overloading

我有以下代码:

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/

相关文章:

c# - 防止在 ASP.NET 中与 ADO.NET 并发执行存储过程

c++ - 为右值参数隐式生成函数重载?

java - Java Composite 的层次结构问题

自定义类的Java函数重载歧义

c++ - 为 Unicode 和 ANSI 重载 toString

c++ - 如何以非内联方式定义模板覆盖的功能

c# - 从 argb 数获取单一颜色值

c# - Delphi 函数转 C#

c# - 批量保存到 MongoDB C# 驱动程序

c# - 如何在 C# 中更改 DataGridViewComboBoxColumn 的行为?