我有一个对象 ex: string str
并且我想在它两次更改其值后将其设置为只读,如此处所示
string str="hello world";
str="hello";
str="hi";
//good
str="sup";
//error
但我也希望能够更改值可以分配给对象的次数 例如:
string str[limit 2]="hello world";
str="hello";
str="hi";
//good
str[limit++];
str="sup";
//good
这可能吗?
最佳答案
不使用字符串,但创建一个具有为您提供此类控制的属性的类非常容易:
class IrregularVariableConstThingy
{
private int _changeCount = 0;
private string _value;
public IrregularVariableConstThingy(int maxChangeCount)
{
MaxChangeCount = maxChangeCount;
}
public int MaxChangeCount {get;set;}
public string Value {
get {
return _value;
}
set {
if(_changeCount = MaxChangeCount)
{
throw new Exception("Now you can't change my value!");
}
_changeCount++;
_value = value;
}
}
}
请注意,此实现不是线程安全的,也不推荐,但它确实演示了基本概念。
关于c# - 在给定指定数量的值后将对象设置为 'read only',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56796079/