private static void Foo(Exception e)
{
e = new Exception("msg1");
}
static void Main(string[] args)
{
try
{
int zero = 0;
int ecks = 1/zero;
}
catch (Exception e)
{
// I thought Exception is passed by reference, therefore Foo changes e to
// point to new Exception instance with message "msg1".
// But it stays the same
Foo(e);
throw e;
}
}
public class MyClass
{
public string Name { get; set; }
}
private static void Foo(MyClass m) { m.Name = "bar"; }
static void Main(string[] args)
{
Voda v = new Voda();
v.Name = "name";
Foo(v); // v.Name gets value "bar"
}
msdn例外はクラスです。
EDIT
private static void Foo(Exception e)
{
while (e != null && e.InnerException != null)
{
// I'm changing where e points.
// Therefore caller Exception should now point to most inner exception
e = e.InnerException;
});
}
使用して、REFキーワード:無効はFoo(REF例外e) – Evk
をあなたは 'ref'を使用していない限り、 C#では何も参照渡しされません。参照型の場合、データへの参照はメソッドに_copied_されます。だからオブジェクトを変更することができます(変更可能な場合)が、呼び出し側メソッドの変数を変更することはできません – MAV
実際には重複していませんが、[見て](http://stackoverflow.com/q/186891/1997232)。 – Sinatr