为什么非要用"明"而不是裁判? [英] Why must use "out" instead of ref?

查看:140
本文介绍了为什么非要用"明"而不是裁判?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一篇关于裁判退房手续报关一些code块。我认为裁判是最有用的。好。为什么我需要使用的。我可以使用总裁判每次:

 命名空间out_ref
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            sinifA sinif =新sinifA();
            INT测试= 100;
            sinif.MethodA(输出测试);
            Console.WriteLine(test.ToString());

            sinif.MethodB(参考测试);
            Console.WriteLine(test.ToString());
            Console.ReadKey();
        }
    }

    类sinifA
    {

        公共无效治法(OUT INT一)
        {
            一个= 200;
        }

        INT _b;
        公共无效方法b(REF INT B)
        {
            _b = B;
            B = 2 * B;
        }
    }

}
 

解决方案

是的,你可以每次都用裁判,但他们有不同的目的。裁判用于当一个参数既是输入和输出端。出时使用的参数是唯一的一个输出。它可以用来传递一个输入,但它使得一个功能的用户不需要使用该功能之前宣布的一个实例,因为你实际上是说,你将保证在创建一个实例。它在TryXXX模式是非常有用的,当你从集合中获取一个值

i wrote some code blocks about ref -out declaration. i think that ref is most useful out. Ok. why i need to use out. i can use always ref everytime:

namespace out_ref
{
    class Program
    {
        static void Main(string[] args)
        {
            sinifA sinif = new sinifA();
            int test = 100;
            sinif.MethodA(out test);
            Console.WriteLine(test.ToString());

            sinif.MethodB(ref test);
            Console.WriteLine(test.ToString());
            Console.ReadKey();
        }
    }

    class sinifA
    {

        public void MethodA(out int a)
        {
            a = 200;
        }

        int _b;
        public void MethodB(ref int b)
        {
            _b = b;
            b = 2*b;
        }
    }

}

解决方案

Yes you can use ref every time but they have different purposes. ref is used for when a parameter is both an input and an output. out is used when the parameter is an output only. It can be used to pass an input but it makes it so the user of a function does not need to declare an instance before using the function because you are in effect saying that you will guarantee an instance is created. It is especially useful in the TryXXX pattern when you are getting a value from a collection

这篇关于为什么非要用"明"而不是裁判?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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