【问题标题】:C# - Object reference not being modifiedC# - 对象引用未被修改
【发布时间】:2014-12-19 06:39:37
【问题描述】:
我有以下代码:
public static void Main() {
Exception exception = new Exception("1", new Exception("2"));
Exception inner = exception.InnerException;
inner = new Exception("3");
Console.WriteLine(exception);
Console.ReadLine();
}
这应该打印带有消息"1" 的异常和带有消息"3" 的内部异常
但是,在打印时,内部异常有消息"2"。
怎么会这样?我不是在修改参考对象吗?当我调用exception.InnerException 时,对象的副本是否返回给我?
【问题讨论】:
标签:
c#
oop
exception
properties
reference
【解决方案1】:
这应该打印带有消息“1”的异常和带有消息“3”的内部异常
不,它不应该 - 因为您根本没有修改 exception 变量引用的对象。相反,您要声明一个变量并使用 exception 为其赋予初始值:
Exception inner = exception.InnerException;
这会将exception.InnerException(这是一个引用)的值复制到inner 变量。然后在下一行中,您将忽略当前值,而只给 inner 一个不同的值:
inner = new Exception("3");
这不会改变exception 的任何内容。 inner 的原始值恰好是从exception.InnerException 属性中获取的这一事实并不影响将新值分配给inner。你也可以这样写:
Exception inner = new Exception("3");
构造异常后,您无法更改Exception.InnerException - InnerException 属性是只读的。即使它是一个可写的属性,你的代码也不会做你想做的事。相反,您需要:
// This won't work because InnerException is read-only, but it would *otherwise*
// have worked.
excetion.InnerException = new Exception("3");
【解决方案2】:
我不是在修改引用对象吗?
不,你不是。
当我调用 exception.InnerException 时,是否将对象的副本返回给我?
不,参考的副本已退还给您。
这是发生了什么:
Exception inner = exception.InnerException;
inner 现在引用exception.InnerException 也引用的对象。
inner = new Exception("3");
inner 现在引用了一个不同的 对象。 id did 引用的对象没有改变。