質問

I have been reading up on passing reference types in C# and I am unsure about a specific situation.

Example Code:

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);

I know that Zed is not changed in y but is x modified? Or is x in still 3 after passing y to Func and treating it as a Bar?

役に立ちましたか?

解決

You only have one, mutable Bar instance through the whole process.

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

y.Zed == 2 and y.x == 2 at the end of this, because those are the values they were assigned in Func. The fact that one was set via a property and the other via a method is unimportant.

他のヒント

I know that Zed is not changed in y but is x modified? Or is x in still 3 after passing y to Func and treating it as a Bar?

X will be modified. It will be 2 due to following line in Func

child.SetX(2); //situation in question.
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top