c#中值类型和引用类型的混淆 [英] confusion with value type and reference type in c#

查看:25
本文介绍了c#中值类型和引用类型的混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对参数有点困惑.在 C# 中使用方法/函数进行编程时,何时必须使用引用参数,何时必须使用值类型参数?

I have bit confusion about parameters. When we should have to use reference parameter and when should have to use value type parameters while programming with methods/functions in c# ?

推荐答案

您需要非常清楚地了解引用类型与值类型之间的区别,以及按值"参数与按引用"的区别" 参数.

You need to be very clear on the distinction between reference types vs value types, and "by value" parameters vs "by reference" parameters.

我有关于这两个主题的文章:

I have articles on both topics:

当使用引用类型的按值"参数时,两者有些交互:在这种情况下,按值复制的值是引用本身;您仍然可以修改引用所指的对象:

The two interact somewhat when using a "by value" parameter which is a reference type: in this case the value which copied by value is the reference itself; you can still modify the object that the reference refers to:

void SomeMethod(StringBuilder x)
{
    x.Append("Modified");
}
...

StringBuilder builder = new StringBuilder();
SomeMethod(builder);
Console.WriteLine(builder.ToString()); // Writes "Modified"

请注意,这 与传递引用语义不同...如果将 SomeMethod 更改为包含:

Note that this isn't the same thing as pass-by-reference semantics... if SomeMethod were changed to include:

x = null;

那么不会使 builder 变量为空.但是,如果您x 参数更改为 ref StringBuilder x(并适当地更改了调用代码),则对 的任何更改x(比如设置为null)被调用者看到.

then that wouldn't make the builder variable null. However, if you also changed the x parameter to be ref StringBuilder x (and changed the calling code appropriately) then any changes to x (such as setting it to null) would be seen by the caller.

在设计您自己的 API 时,我强烈建议您几乎从不使用 refout 参数.它们可能偶尔有用,但通常它们表明您正在尝试从单个方法返回多个值,通常最好使用专门封装这些值的类型,或者可能是Tuple 类型(如果您使用的是 .NET 4).当然,此规则有例外,但这是一个很好的起点.

When designing your own API, I would strongly advise you to almost never use ref or out parameters. They can be useful occasionally, but usually they're an indication that you're trying to return multiple values from a single method, which is often better done with a type specifically encapsulating those values, or perhaps a Tuple type if you're using .NET 4. There are exceptions to this rule, of course, but it's a good starting point.

这篇关于c#中值类型和引用类型的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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