4

更新だから完全にツールの瞬間を引っ張った。Out/Ref に対する参照という意味です。「ref」と書かれているものはすべて、私が実際に参照することを意味していました

SomeMethod(オブジェクト someObject)

SomeMethod(out someObject)

ごめん。コードを変更したくないだけなので、答えはすでに意味があります。

私が理解している限り、ポインターを「コピー」し、そのポインターを使用するためにスタック上に新しいスペースを作成する ref とは異なりますが、ポインターは変更しません。

SomeMethod()
{
 SomeThing outer = new SomeThing();
 RefMethod(ref outer)
}

RefMethod(ref inner)  //new space on stack created and uses same pointer as outer
{
   inner.Hi = "There"; //updated the object being pointed to by outer
   inner = new SomeThing();//Given a new pointer, no longer shares pointer with outer
                           //New object on the heap
}

Out はポインターをコピーし、ポインターが指す場所を操作できます。

SomeMethod()
{
 SomeThing outer = new SomeThing();
 RefMethod(out outer)
}

RefMethod(out inner)  //same pointer shared
{

   inner = new SomeThing();//pointer now points to new place on heap  
                           //outer now points to new object
                           //Old object is orphaned if nothing else points to it
}

オブジェクトに関してはそれで問題ありませんが、スタック上にあるだけであることを示すものがないため、値型についてはどうでしょうか?

4

3 に答える 3

9

Just because the variable lives on the stack (if it's a local variable) doesn't mean you can't create a pointer to it - and indeed that's the case with reference types as well.

The pointer within RefMethod is to the "outer" variable - and the variable itself lives on the stack as it's an uncaptured local variable.

As Leppie said, ref and out are identical except for the rules on definite assignment - in fact, the only difference in IL is an attribute applied to out parameters.

See my article on parameter passing for more details about ref/out in general.

于 2009-01-12T19:52:45.607 に答える
3

私の知る限り、ref と out はまったく同じですが、out パラメータは初期化できないという点が異なります。したがって、両方がスタックに置かれます。

于 2009-01-12T19:52:22.003 に答える
1

実際に参照型で ref または out を使用すると、ポインターも作成されます...オブジェクトではなく、オブジェクトへの参照です! だから、それはある種の

RefMethod(SomeThing **inner)
{
}

C++ では、値型では次のようになります。

RefMethod2(int *inner)
{
}

値型の場合。

于 2009-01-12T20:40:08.617 に答える