在C#中使用'裁判'关键字 [英] Use of 'ref' keyword in C#

查看:158
本文介绍了在C#中使用'裁判'关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能显示的文件:
  为什么要传递一个对象时?
使用ref关键字   何时传入 ref关键字

什么是C#中的裁判的关键字的正确用法。我认为出现了大量的讨论线程这一点,但什么是我不明白的是:

  1. 是,如果你传递一个参考对象所需要的ref关键字?我的意思是,当你在堆上创建一个对象,是不是总是通过引用传递。这是否有明确标记为参考?
解决方案

使用 REF 指的引用的传递给函数。

默认行为是函数接收一个新的引用同一个对象。这意味着,如果你更改参考值(例如,将其设置为一个新的对象),那么你不再指向原来,源对象。当您通过使用 REF 然后改变参考的价值变动源代码参考 - 因为他们是同样的事情

考虑一下:

 公共类的事
{
    公共字符串属性{获取;集;}
}

公共静态无效围棋(事嘛)
{
    事情=新事物();
    thing.Property =更改;
}

公共静态无效围棋(REF事情事)
{
    事情=新事物();
    thing.Property =更改;
}
 

然后,如果你运行

 变种G =新事物();

//这不会改变摹
转到(G);

//这个*将*改变摹
去(REF G);
 

Possible Duplicates:
Why use ref keyword when passing an Object?
When to pass ref keyword in

What is the correct usage of the 'ref' keyword in C#. I believe there has been plenty of discussion threads on this, but what is not clear to me is:

  1. Is the ref keyword required if you are passing in a reference object? I mean when you create an object in the heap, is it not always passed by reference. Does this have to be explicitly marked as a ref?

解决方案

Using ref means that the reference is passed to the function.

The default behaviour is that the function receives a new reference to the same object. This means if you change the value of the reference (e.g. set it to a new object) then you are no longer pointing to the original, source object. When you pass using ref then changing the value of the reference changes the source reference - because they are the same thing.

Consider this:

public class Thing
{
    public string Property {get;set;}
}

public static void Go(Thing thing)
{
    thing = new Thing();
    thing.Property = "Changed";
}

public static void Go(ref Thing thing)
{
    thing = new Thing();
    thing.Property = "Changed";
}

Then if you run

var g = new Thing();

// this will not alter g
Go(g);

// this *will* alter g
Go(ref g);

这篇关于在C#中使用'裁判'关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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