[英]In C# 4.0, is there any way to make an otherwise private member of one class available only to a specific other class?
[英]C#: Is there a way to make a field of one instance readonly when referenced by other instances of any class?
有沒有辦法讓tastesGood
只能在Apple
內部重新定義,但仍然可以被Jim
引用?
public class Apple {
public bool tastesGood = true;
void ChangeYourMind() {
tastesGood = false;
}
}
public class Jim {
void EatApple() {
if (tastesGood) {
Speak("mmmmm!");
} else {
Speak("Yuck!");
}
}
}
一般來說,您不應該公開類中的字段。 而是將值公開為具有公共 getter 的屬性,但使用私有 setter 。 C# 對屬性和字段使用不同的語法。
public class Apple {
public bool TastesGood { get; private set; } = true;
public void ChangeYourMind()
{
this.TastesGood = false;
}
}
其他提示:
PascalCase
(而不是camelCase
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.