C#传值/ REF? [英] C# pass by value/ref?

查看:88
本文介绍了C#传值/ REF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

常见的问题,但我可以用一个英语的解释..

Common question but I could use an "english" explanation..

北京时间它像Java,其中

Ist it like Java where

Cat myCat

实际上是一个指向猫?

actually is a pointer to Cat?

如果我真的在C#创建拷贝构造函数?

Should I really create copy constructors in c#?

据我所知,我们按值传递,但现在我的问题是,我们是路过的指针的值或对象的完整副本?

I understand we are passing by value, but now my question is are we passing by pointer value or full copy of the object?

如果是后者,心不是太贵了性能/内存明智?就是当你必须使用ref关键字?

if its the latter, isnt that too expensive performance/memory wise? Is that when you have to use the ref keyword?

推荐答案

由于@rstevens回答,如果它是一个类,myCat是一个参考。但是,如果你传递myCat一个方法调用,然后引用本身是按值传递 - 即参数本身会引用同一个对象,但它是一个完全新的参考,因此,如果您指定为null,或创建一个新的对象,老myCat参考仍将指向原始对象。

As @rstevens answered, if it is a class, myCat is a reference. But if you pass myCat to a method call, then the reference itself is passed by value - i.e. the parameter itself will reference the same object, but it's a completely new reference, so if you assign it to null, or create a new object, the old myCat reference will still point to the original object.

SomeMethod(myCat);

void SomeMethod(Cat cat)
{
    cat.Miau(); //will make the original myCat object to miau
    cat = null; //only cat is set to null, myCat still points to the original object
}

乔恩斯基特大约有一个好文章

这篇关于C#传值/ REF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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