“ref"有什么用?对于 C# 中的引用类型变量? [英] What is the use of "ref" for reference-type variables in C#?

查看:13
本文介绍了“ref"有什么用?对于 C# 中的引用类型变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白,如果我传递一个值类型(intstruct 等)作为参数(没有 ref 关键字),该变量的副本将传递给该方法,但如果我使用 ref 关键字,则会传递对该变量的引用,而不是新的引用.

I understand that if I pass a value-type (int, struct, etc.) as a parameter (without the ref keyword), a copy of that variable is passed to the method, but if I use the ref keyword a reference to that variable is passed, not a new one.

但是对于引用类型,如类,即使没有 ref 关键字,引用也会传递给方法,而不是副本.那么 ref 关键字和引用类型有什么用?

But with reference-types, like classes, even without the ref keyword, a reference is passed to the method, not a copy. So what is the use of the ref keyword with reference-types?

举个例子:

var x = new Foo();

以下有什么区别?

void Bar(Foo y) {
    y.Name = "2";
}

void Bar(ref Foo y) {
    y.Name = "2";
}

推荐答案

您可以使用 y 更改 foo 指向的内容:

You can change what foo points to using y:

Foo foo = new Foo("1");

void Bar(ref Foo y)
{
    y = new Foo("2");
}

Bar(ref foo);
// foo.Name == "2"

这篇关于“ref"有什么用?对于 C# 中的引用类型变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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