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例外是类。
编辑
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关键字:无效美孚(REF例外五) – Evk
除非你使用'ref', C#中没有任何内容是通过引用传递的。对于参考类型,数据的_reference_被复制到方法中。所以你可以改变对象(如果它是可变的),但你不能在调用方法中改变变量 – MAV
不是真的重复,但[看看](http://stackoverflow.com/q/186891/1997232)。 – Sinatr