如何将C# 12主构造函数参数设置为readonly?
如何让C# 12主构造函数参数成为只读变量?
我正在熟悉C# 12的主构造函数变量。以下是我的代码:
public class BankAccountNew(string accountID, string owner) { public void DoSomethingWrong() { accountID = "Wrong"; } } public class BankAccounOld { private readonly string accountID; private readonly string owner; public BankAccounOld(string accountID, string owner) { this.accountID = accountID; this.owner = owner; } public void DoSomethingWrong() { accountID = "Wrong"; // 这里会触发编译错误 } }
我希望DoSomethingWrong方法因修改只读参数触发编译错误,旧类BankAccounOld已实现此效果,但代码冗余。想修改BankAccountNew,让accountID被识别为readonly,修改时触发编译错误,该怎么做?
解决方案
有两种简洁的方式实现需求:
方法1:给主构造函数参数添加readonly修饰符
直接在主构造函数的参数前加上readonly关键字,参数会被视为只读实例变量,类方法中无法修改:
public class BankAccountNew(readonly string accountID, readonly string owner) { public void DoSomethingWrong() { accountID = "Wrong"; // 触发编译错误:无法对只读变量赋值 } }
方法2:显式声明readonly字段并绑定主构造函数参数
如果需要自定义字段访问修饰符(比如设为private),可以显式声明readonly字段,用主构造函数参数直接赋值:
public class BankAccountNew(string accountID, string owner) { private readonly string _accountID = accountID; private readonly string _owner = owner; public void DoSomethingWrong() { _accountID = "Wrong"; // 触发编译错误 } }
第一种方法更贴合C# 12主构造函数的简化特性,无需额外字段声明就能实现只读约束,完美替代旧类的冗余写法。
内容的提问来源于stack exchange,提问作者Daan
相关产品推荐
相关产品推荐

