当使用ref和当它不是在C#必要 [英] When to use ref and when it is not necessary in C#

查看:181
本文介绍了当使用ref和当它不是在C#必要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它是程序的我的记忆状态,也有我通过对象来修改状态其它一些工人功能。我一直在传递给它由裁判工人功能。不过我碰到下面的函数。

I have a object that is my in memory state of the program and also have some other worker functions that I pass the object to to modify the state. I have been passing it by ref to the worker functions. However I came across the following function.

byte[] received_s = new byte[2048];
IPEndPoint tmpIpEndPoint = new IPEndPoint(IPAddress.Any, UdpPort_msg);
EndPoint remoteEP = (tmpIpEndPoint);

int sz = soUdp_msg.ReceiveFrom(received_s, ref remoteEP);

这混淆了我,因为这两个 received_s remoteEP 从函数返回的东西。为什么 remoteEP 需要 REF received_s 不?

It confuses me because both received_s and remoteEP are returning stuff from the function. Why does remoteEP need a ref and received_s does not?

我也是,所以我有让球从我的头一个问题一个C程序员。

I am also a c programmer so I am having a problem getting pointers out of my head.

编辑:
它看起来像在C#中的对象指针引擎盖下的对象。所以,当你传递一个对象到一个功能,您可以再通过指针修改对象的内容,并传递给函数的唯一的事情就是指向对象,因此对象本身不被复制。您可以使用ref或out,如果你希望能够转出或创建这就好比双指针功能的新对象。

It looks like that objects in C# are pointers to the object under the hood. So when you pass an object to a function you can then modify the object contents through the pointer and the only thing passed to the function is the pointer to the object so the object itself is not being copied. You use ref or out if you want to be able to switch out or create a new object in the function which is like a double pointer.

推荐答案

简短的回答:读取参数传递我的文章

Short answer: read my article on argument passing.

龙回答:当引用类型参数是按值传递,仅引用传递,的的对象的副本。这就像C或C指针传递(按价值计算)++。变化本身将不会被呼叫方可以看出,参数的值,但是变化的对象,该对象的基准点的的可见

Long answer: when a reference type parameter is passed by value, only the reference is passed, not a copy of the object. This is like passing a pointer (by value) in C or C++. Changes to the value of the parameter itself won't be seen by the caller, but changes in the object which the reference points to will be seen.

当一个参数(任何种类的)传递的通过的参考,这意味着,对参数的任何变化由呼叫者看出 - 的的变化而变化的参数给变量

When a parameter (of any kind) is passed by reference, that means that any changes to the parameter are seen by the caller - changes to the parameter are changes to the variable.

的文章解释了这一切的更详细,当然是:)

The article explains all of this in more detail, of course :)

有用的答案:你几乎从来没有需要使用REF /退出。这基本上让另一个返回值的方法,并通常应避免precisely,因为这意味着该方法的可能是试图做太多。这并非总是如此(的TryParse 等都是合理的使用的出典型的例子),但使用REF /输出应是一种相对罕见。

Useful answer: you almost never need to use ref/out. It's basically a way of getting another return value, and should usually be avoided precisely because it means the method's probably trying to do too much. That's not always the case (TryParse etc are the canonical examples of reasonable use of out) but using ref/out should be a relative rarity.

这篇关于当使用ref和当它不是在C#必要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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