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

查看:137
本文介绍了在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:

  • Reference types and value types
  • Parameter passing

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

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参数.它们 有时会很有用,但是通常它们表明您正在尝试从单个方法返回多个值,通常最好使用专门封装这些值的类型来完成,或者如果您使用的是.NET 4,请输入Tuple.当然,该规则也有例外,但这是一个很好的起点.

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天全站免登陆