C# object modification
I think this is really a very lame question, but I guess on SO
I will receive the answer faster than by googling it myself :)
Let's say I have some class with a constructor:
public class TestClass {
private readonly IRepository repository;
public TestClass(IRepository repository)
{
this.repository = repository;
// Here is the non-obvious line - it invokes some
// method, which changes the internal contents of
// the repository object.
reposi开发者_开发百科tory.AddSomething(...);
}
}
And now:
IRepository sqlRepository = new SqlRepository(...);
TestClass testClass = new TestClass(sqlRepository);
1) I'm not good at value / reference passing in C#
- so please could someone give a step-by-step explanation of what happens in this case.
2) Does the sqlRepository
object get modified (I assume not) and is there a way to make the constructor of TestClass
modify it (I know it's evil, just for me to know)?
3) Would the repository.AddSomething(...)
and this.repository.AddSomething(...)
lines in the constructor have the same effect and why?
4) What effect does readonly
have on the attempts of the repository changes in this example?
In this case the reference to
sqlRespository
is passed into the ctor.Not yet. When you call
AddSomething()
, that method is indeed modifying the original instance. We still only have one object and everyone is touching that one. It's an important distinction that since everyone has a reference to the same object, any changes they make will be made to that object. However, if they simply overwrite that variable with a different object, that only applies locally. Remember, variables are like slots. We can have lots of slots that all point back to the same object, but replacing one slot with a pointer to a different object doesn't affect the other slots.If you first set
this.repository = repository
then both the local parameter calledrepository
and member variable (field) calledrepository
hold a reference to the same object. We usethis.
to be clear we mean the member variable (field) and not the local parameter or variable.readonly
means that member variable / field can only be assigned from the constructor. Think of the member variable as a slot where we can put an object. If the slot isreadonly
, that means it can only be filled during the ctor call. After that it can't be replaced. That does not mean that the object inside of it is somehow "read-only". The object can still be modified, it just can't be replaced by another object.
精彩评论