C#的引用

来源:互联网 发布:大数据时时彩在线计划 编辑:程序博客网 时间:2024/06/06 02:21

ref相当于C/C++的引用(&)
The ref keyword causes arguments to be passed by reference. The effect is that any changes to the parameter in the method will be reflected in that variable when control passes back to the calling method.
举例如下:
class RefExample
    {
        static void Method(ref int i)
        {
            // Rest the mouse pointer over i to verify that it is an int.
            // The following statement would cause a compiler error if i
            // were boxed as an object.
            i = i + 44;
        }

        static void Main()
        {
            int val = 1;
            Method(ref val);
            Console.WriteLine(val);

            // Output: 45
        }
    }
out相当于ref,但有所不同,ref使用时变量必须初始化,而out不必。
The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. For example:
class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}
呵呵,这给我们一个函数返回多值带来了方便,如要使用指针可使用关键字unsafe即可像C/C++运行指针了...

原创粉丝点击