为什么必须使用"out"而不是ref?

Pen*_*uen 4 .net c# oop visual-studio-2008 visual-studio

我写了一些关于ref -out声明的代码块.我认为ref最有用.好.为什么我需要用完.我每次都可以使用ref:

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;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Cra*_*nec 13

是的,你每次都可以使用ref,但它们有不同的用途.ref用于当参数既是输入又是输出时.当参数仅为输出时使用out.它可用于传递输入,但它使得函数的用户不需要在使用函数之前声明实例,因为您实际上说您将保证创建实例.当您从集合中获取值时,它在TryXXX模式中特别有用

  • 另外,out param必须由需要它的函数初始化,否则你会遇到编译错误,这是一件好事. (3认同)

sha*_*esh 6

如果out附加了一个参数,则在将其传递给接受它的方法之前,不需要初始化它.

The out keyword causes arguments to be passed by reference. 
This is like the ref keyword, except that ref requires that the variable be initialized 
before it is passed.
Run Code Online (Sandbox Code Playgroud)

来自:http://msdn.microsoft.com/en-us/library/ee332485.aspx