使用值和引用参数类型重载的方法 [英] Methods overloading with value and reference parameter types

查看:62
本文介绍了使用值和引用参数类型重载的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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 关键字区分,但此代码运行良好.

This code work well despite that methods signature are differenciated only be the out keyword.

但以下代码不起作用:

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 这样的关键字是方法签名的一部分吗?

Why this code didn't work ? Are keywords like ref and out part of methods signatures?

推荐答案

out 参数修饰符(C# 参考)

虽然 ref 和 out 关键字导致不同的运行时行为,在编译时它们不被视为方法签名的一部分.因此,如果唯一的区别是方法不能重载是一种方法采用 ref 参数,另一种方法采用 out论证.

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#参考)

一个类的成员不能有仅通过ref和 如果两者之间的唯一区别发生,则会发生编译器错误一个类型的成员是其中一个有一个 ref 参数和other 有一个 out 参数.

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.

这篇关于使用值和引用参数类型重载的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆