C#构造方法赋初始值

namespace ConsoleApplication1
{
    public class Test
    {

        public int Id { get; set; }
        public string Name { get; set; }
        public string Country { get; set; }

        //public Test(int id, string name) : this(Id, Name, Country: "china")
        //{

        //}
        public Test(int id, string name, string country)
        {
            Id = id;
            Name = name;
            Country = country;
        }

        public Test(int id, string name) : this(id, name, "默认值")
        {

        }

        public override string ToString()
        {
            return this.Id + "---" + this.Name + "---" + this.Country;
        }
    }
}

using System;

namespace ConsoleApplication1
{
    static class Program
    {

        static void Main(string[] args)
        {

            Test test = new Test(1, "wang");
            Console.WriteLine(test);
            Test test1 = new Test(1, "wang121","lallaallaalal");
            Console.WriteLine(test1);
            Console.ReadKey();
        }
    }
}

### C# 字典初始化后并非自动成为只读 在C#中,字典初始化之后并不会默认变成只读状态。然而,在某些场景下开发者可能会希望将字典设置成不可更改的状态以防止意外修改。这可以通过`ReadOnlyDictionary<TKey, TValue>`类或是调用`.AsReadOnly()`方法实现[^1]。 当使用对象初始化器语法向字典添加项时,实际上是在实例化过程中执行了一系列的`Add`操作。一旦完成初始化并显式转换为只读形式,则后续尝试对该集合进行任何变更都将引发异常[^2]。 如果需要创建一个可变的字典并在初始化完成后继续对其进行增删改操作,只需保持原生的`Dictionary<TKey, TValue>`类型即可;而要将其设为只读,则可以采用如下方式: ```csharp using System; using System.Collections.Generic; class Program { static void Main(string[] args){ // 创建并填充一个普通的 Dictionary var originalDict = new Dictionary<string, string>(){ {"key1", "value1"}, {"key2", "value2"} }; // 转换为 ReadOnlyDictionary 或者 使用 AsReadOnly 方法 IReadOnlyDictionary<string, string> readOnlyDict = new ReadOnlyDictionary<string, string>(originalDict); try{ // 下面这条语句会抛出 NotSupportedException 异常 readOnlyDict["newKey"] = "newValue"; }catch(NotSupportedException ex){ Console.WriteLine($"无法修改只读字典: {ex.Message}"); } } } ``` 上述代码展示了如何定义一个常规的字典,并通过构造函数传入该字典来获得一个新的`ReadOnlyDictionary<TKey, TValue>`实例。对于后者来说,所有的写入请求都会被拒绝并且触发相应的异常处理逻辑。 为了确保程序能够正常工作而不受制于这些约束条件,应该根据实际需求选择合适的方式来管理数据结构——即决定何时以及是否应当使某个特定的数据容器进入只读模式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值