0

我一直在阅读有关在 C# 中传递引用类型的内容,但我不确定具体情况。

示例代码:

public class Foo
{
  int x;
  public SetX(int value)
  {
    x = value;
  }
  public int Zed
  {
    get;
    set;
  }
public class Bar : Foo
{
  //suffice it to say, this is SOME inherited class with SOME unique elements
}

...
void Func (Foo item)
{
  Bar child = item as Bar;
  child.Zed = 2;
  child.SetX(2); //situation in question.
}
...
Bar y = new Bar();
y.Zed = 1;
y.SetX(3);
Func(y);

我知道那Zed没有改变,y但被x修改了?还是在传递到并将其视为一个之后x仍然存在?3yFuncBar

4

2 回答 2

1

Bar在整个过程中,您只有一个可变实例。

Foo y = new Bar();
y.Zed = 1;
y.SetX(3);
Func(y);

y.Zed == 2最后y.x == 2,因为这些是它们被分配的值Func。一个是通过属性设置的,另一个是通过方法设置的这一事实并不重要。

于 2013-11-05T17:10:28.087 回答
1

我知道 Zed 在 y 中没有改变,但是 x 被修改了?或者在将 y 传递给 Func 并将其视为 Bar 之后,x 仍然是 3 吗?

X 将被修改。这将是2由于以下行Func

child.SetX(2); //situation in question.
于 2013-11-05T17:10:18.123 回答