当通过参考关键字 [英] When to pass ref keyword in

查看:118
本文介绍了当通过参考关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过的参数passng并没有通过裁判之间的差异,但是,当我会想使用它们?

I've read the difference between passng and not passing ref in parameters, however, when would I want to use them?

例如,我在可能被重构到它自己的方法的方法有一些逻辑。 ReSharper的4.5所做的参数ref类型之一,但我没想到我会做的这一点,如果我重构手工做了。

For example, I had some logic in a method which could be refactored into its own method. Resharper 4.5 made one of the parameters a ref type but I didn't think I would have of done this if I did the refactoring manually.

显然我错过了一些了解。也许会发生什么的例如,当某些类型或某些情况下在编码小姐ref关键字将帮助?

Obviously I am missing some understanding. Perhaps an example of what happens when certain types or certain scenarios in coding miss the ref keyword will help?

感谢

推荐答案

让我打破下来到两个问题:

Let me break that down into two questions:

1)当编写一个方法时应该之一中使用REF /输出形式参数的声明?

1) When should one use ref/out formal parameter declarations when writing a method?

使用REF /输出,当你渴望你的方法,以便能够读取和写入的变量的从调用者传递,而不是仅仅读的

Use ref/out when you desire your method to be able to read and write a variable passed in from the caller, rather than merely reading a value.

2)为什么一个法提取重构产生ref参数?

2) Why does an "extract method" refactoring produce a ref parameter?

我不知道ReSharper的细节,但我可以做一个猜测。请看下面的邪恶可变的值类型:

I don't know the details of Resharper, but I can make a guess. Consider the following evil mutable value type:

struct S 
{ 
  private int x;
  public int X() { return this.x; } 
  public void M() { this.x += 1; } 
}

您有一个方法:

void Foo() 
{
    S s = new S();
    Fred(s);
    Blah(s);
    Bar(s);
    s.M();
    Console.WriteLine(s.X()); // prints 1
}

和你做的提取方法的中间位:

and you do "extract method" on the middle bit:

void NewMethod(ref S s)
{
    Blah(s);
    Bar(s);
    s.M();
}

void Foo() 
{
    S s = new S();
    Fred(s);
    NewMethod(ref s);
    Console.WriteLine(s.X()); // still prints 1
}

如果你不是没有裁判,然后调用NewMethod做了一个方法(S)将通过s的副本NewMethod。请记住,值类型是按值复制;这就是为什么我们称他们为值类型。这将是被突变的副本,然后s.X()返回零。这是一个重构引入程序中的语义变化一个坏主意,这是困难的重构引擎知道一个给定的方法是否依赖于价值型的可变性与否。

If instead you made a method without "ref" then calling NewMethod(s) would pass a copy of s to NewMethod. Remember, value types are copied by value; that's why we called them "value types". It would be the copy that gets mutated, and then s.X() returns zero. It is a bad idea for a refactoring to introduce a semantic change in a program, and it is difficult for a refactoring engine to know whether a given method relies on the mutability of a value type or not.

这是另一个原因,你应该避免可变的值类型。

This is just another reason why you should avoid mutable value types.

这篇关于当通过参考关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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