c# - 在给定指定数量的值后将对象设置为 'read only'

标签 c# string constants

我有一个对象 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/

相关文章:

c# - 无法将 'System.Int16' 类型的对象转换为 'System.String' 类型

java - 字符串键混合大写会覆盖 Hashmap 中的条目

c++ - constexpr 比 const 多 "constant"吗?

c++ - 如何在 IDL 中声明宽字符常量

c - 在c中的snprintf中使用const char数组

C# 正则表达式公式

c# - 通过多线程下载文件

c# - 使用包含的 xsd 文件编译模式

c - 这个宏是什么 #define type_string(name) { #name , name }

python - 在字符串中逐个字符并使用 python 交换空格