C#构造函数,对象参数通过引用或值传递 [英] C# constructor, object parameter is passed by reference or value

查看:293
本文介绍了C#构造函数,对象参数通过引用或值传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有类和构造它接受一个对象作为输入参数 - ?是按引用传递的对象或者是它按值传递



和是真的假设类方法,除非使用ref关键字输入参数是按值默认传递的对象?对了关键字



什么?这是否仍意味着它是按引用传递?


解决方案

如果你有类和构造函数它接受一个对象作为输入参数 - ?是按引用传递的对象或者是它按值传递




所有的参数传递在C#中值,除非参数标记退出 REF



这是一个巨大的混乱之源。我会更明确规定的东西一点点。



所有的参数都有自己的价值,除非复制参数标有退出 REF 。对于值类型,这意味着传递的值的副本。对于引用类型,这意味着引用的副本。对于最后一点,引用类型的值是参考。




和是真的假设类方法,输入参数是按值默认传递的对象,除非 REF 使用关键字?




此外,所有参数都在C#中值传递的,除非参数标记与退出 REF 。对于标有 REF 参数,该参数的引用传递给方法,现在你可以认为参数作为别名。因此,当你说

 无效M(REF INT M){M = 10; } 

INT N = 123;
M(REF N);

您可以在<$认为 M 的C $ç> M 为 N 。这就是 M N 只是两个对同一存储位置不同的名字。



这是从

 字符串s =非常不同的你好,世界!; 
串T = S;

在这种情况下,取值 T 是不是同一个存储位置alises。这些是碰巧引用相同的物体的两个不同的变量。




有关`out关键字什么?这是否仍意味着它是按引用传递?




REF之间的唯一区别退出 REF 要求在传递之前首先要初始化变量。


If you have class and a constructor which takes in an object as a input param - is that object passed by reference or is it passed by value?

And is it true to assume that for class methods, object input parameters are passed by value by default unless the ref keyword is used?

What about the out keyword? Does this still mean that it is passed by reference?

解决方案

If you have class and a constructor which takes in an object as a input param - is that object passed by reference or is it passed by value?

All parameters are passed by value in C# unless the parameter is marked with out or ref.

This is a huge source of confusion. I'll state things a little more explicitly.

All parameters have their value copied unless the parameter is marked with out or ref. For value types, this means that a copy of the value being passed is made. For reference types this means that a copy of the reference is made. For this last point, the value of a reference type is the reference.

And is it true to assume that for class methods, object input parameters are passed by value by default unless the ref keyword is used?

Again, all parameters are passed by value in C# unless the parameter is marked with out or ref. For a parameter marked with ref, a reference to the parameter is passed to the method and now you can think of that parameter as an alias. Thus, when you say

void M(ref int m) { m = 10; }

int n = 123;
M(ref n);

you can think of m in M as an alias for n. That is m and n are just two different names for the same storage location.

This is very different from

string s = "Hello, world!";
string t = s;

In this case, s and t are not alises for the same storage location. These are two different variables that happen to refer to the same object.

What about the `out keyword? Does this still mean that it is passed by reference?

The only difference between ref and out is that ref requires the variable to be initialized before being passed.

这篇关于C#构造函数,对象参数通过引用或值传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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