「ref」キーワードと参照タイプ[重複
-
09-10-2019 - |
質問
この質問にはすでに答えがあります:
- C#の参照型変数に「ref」の使用は何ですか? 10の回答
私のチームの誰かが、参照タイプでrefキーワードの独特の使用につまずいた
class A { /* ... */ }
class B
{
public void DoSomething(ref A myObject)
{
// ...
}
}
誰かがSANEがそのようなことをする理由はありますか? C#でこれに使用できません
解決
させて
class A
{
public string Blah { get; set; }
}
void Do (ref A a)
{
a = new A { Blah = "Bar" };
}
それから
A a = new A { Blah = "Foo" };
Console.WriteLine(a.Blah); // Foo
Do (ref a);
Console.WriteLine(a.Blah); // Bar
しかし、ただしそうなら
void Do (A a)
{
a = new A { Blah = "Bar" };
}
それから
A a = new A { Blah = "Foo" };
Console.WriteLine(a.Blah); // Foo
Do (a);
Console.WriteLine(a.Blah); // Foo
他のヒント
彼らが変更したい場合にのみ 参照 asに渡されたオブジェクトに myObject
別のものに。
public void DoSomething(ref A myObject)
{
myObject = new A(); // The object in the calling function is now the new one
}
これは彼らがやりたいことではない可能性があり、 ref
必要ありません。
ref
メソッドがメソッドに渡された変数に保存されている参照を変更することになっている場合、キーワードは有用です。使用しない場合 ref
参照を変更することはできません。オブジェクト自体がメソッドの外に表示されるだけです。
this.DoSomething(myObject);
// myObject will always point to the same instance here
this.DoSomething(ref myObject);
// myObject could potentially point to a completely new instance here
これに特有のものはありません。メソッドからいくつかの値を返したい場合、または引数として渡したオブジェクトに戻り値を再割り当てしたくない場合、変数を参照してください。
このような:
int bar = 4;
foo(ref bar);
それ以外の:
int bar = 4;
bar = foo(bar);
または、いくつかの値を取得したい場合:
int bar = 0;
string foobar = "";
foo(ref bar, ref foobar);
所属していません StackOverflow