【发布时间】:2010-12-12 15:54:24
【问题描述】:
我认为这确实是一个非常蹩脚的问题,但我想在SO 上我会比自己用谷歌搜索更快地收到答案:)
假设我有一个带有构造函数的类:
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.
repository.AddSomething(...);
}
}
现在:
IRepository sqlRepository = new SqlRepository(...);
TestClass testClass = new TestClass(sqlRepository);
1) 我不擅长传递 C# 的值/引用 - 所以请有人逐步解释发生的事情这种情况。
2) sqlRepository 对象是否被修改(我假设没有) 有没有办法让TestClass 的构造函数修改它(我知道这是邪恶的,只是让我知道)?
3) 构造函数中的repository.AddSomething(...) 和this.repository.AddSomething(...) 行会产生相同的效果吗?为什么?
4)readonly 对本示例中的存储库更改尝试有什么影响?
【问题讨论】:
标签: c# constructor pass-by-reference