【发布时间】:2013-04-10 11:05:46
【问题描述】:
我意识到这可能是非常基本的事情,但我不确定实现以下目标的最佳实践。
我有以下带有字符串属性myString的类:
public class MyClass
{
public string myString
{
get {
return myString;
}
}
public void AFunction()
{
// Set the string within a function
this.myString = "New Value"; // Error because the property is read-only
}
}
我希望myString 属性符合以下条件:
- 内部可设置
- 内部可获取
- 不可在外部设置
- 可从外部获取
所以我希望能够在类内设置变量myString,并使其值在类外只读。
有没有办法在不使用单独的 get 和 set 函数并将 myString 属性设为私有的情况下实现这一点,如下所示:
public class MyClass
{
private string myString { get; set; }
public void SetString()
{
// Set string from within the class
this.myString = "New Value";
}
public string GetString()
{
// Return the string
return this.myString;
}
}
上面的示例允许我在内部设置变量,但不能从类外部对实际属性 myString 进行只读访问。
我尝试了protected,但这并不能从外部访问该值。
【问题讨论】:
标签: c# class properties