C# 中只读编码的好处

发布日期:2026-07-14 01:57:03   来源 : 杭州电子商务研究院    浏览量 :7
杭州电子商务研究院 发布日期:2026-07-14 01:57:03  
7

介绍

大多数语言都支持只读编程或使用关键字、文字、运算符等进行编码。然而,这是一个非常有争议的话题。有些人开始使用 C# 作为他们的第一门语言进行开发,而其他人则凭借其他语言的开发经验直接转向这种语言。结果就是对这种编码风格的不同假设。

在本指南中,我们将了解 C# 中只读编码的含义以及如何安全地利用它。有两个关键字支持只读编程,即constreadonly,我们将逐一进行分解,然后组装一个小应用程序进行演示。

常量

借助const关键字,我们可以声明一个常量字段或常量局部变量。它们不被视为变量,也不能被修改;它们的值在整个执行周期中保持不变。我们应该避免创建常量来存储我们预计会随时间变化的信息,因为当发生变化时,异常会阻止我们。

常量有四种类型:

  1. 数字
  2. 细绳
  3. 布尔值
  4. 空引用

您可以按照以下方式在 C# 中声明常量。

      const int a = 10;
const string b = "My Constant!";
private const string Name = "Daniel";
private const int Salary = 100000;
    

您还可以选择在同一行声明多个常量。

      const double a = 1.0, b = 2.0, c = 3.0;
    

由于const所暗示的限制以及对开发人员的限制,因此引入了一个新的关键字。

只读

'readonly' 修饰符总共可以在四种上下文中使用:

  1. 字段声明
  2. 只读结构声明
  3. Readonly 成员定义
  4. Ref 只读方法返回

当我们使用字段声明上下文时,我们需要知道赋值唯一可以发生的时间是声明时或调用同一个类的构造函数时。

      using System;

namespace Pluralsight
{
    public class ReadOnlyProgramming
    {
        readonly string Name;
        readonly int Age;
        readonly int Salary;
        public ReadOnlyProgramming()
        {
            Name = "Default Name";
            Age = 99;
            Salary = 10000;
        }
        public ReadOnlyProgramming(string name, int age, int salary)
        {
            Name = name;
            Age = age;
            Salary = salary;
        }
        public static void Main()
        {
            ReadOnlyProgramming a = new ReadOnlyProgramming();
            ReadOnlyProgramming b = new ReadOnlyProgramming("Florian", 28, 200000);

            Console.WriteLine($"The variable: {nameof(a)} holds: {a.Name} with age: {a.Age} and salary: {a.Salary} USD/yr !");
            Console.WriteLine($"The variable: {nameof(b)} holds: {b.Name} with age: {b.Age} and salary: {b.Salary} USD/yr !");
            //a.Name = "Naomi"; // uncommenting this results in an error
            Console.ReadKey();
        }
    }
}
    

代码执行时会产生以下输出。

      The variable: a holds: Default Name with age: 99 and salary: 10000 USD/yr !
The variable: b holds: Florian with age: 28 and salary: 200000 USD/yr !
    

我们的类中有两个构造函数。一个不带参数的构造函数在调用后为只读属性设置默认值,第二个构造函数接受三个参数并使用它们初始化属性。这是允许的,但如果我们在创建实例后修改任何标记为只读的属性,就会出现以下错误。

      A readonly field cannot be assigned to (except in a constructor or a variable initializer)
    

当我们使用只读结构上下文时,规则是我们将有一个不可变的结构,其中所有实例字段都需要标记为只读,否则会出现以下错误。

      Instance fields of readonly structs must be readonly.
    

让我们创建一个结构来存储有关我们基础设施的静态服务器信息。

      using System;

namespace Pluralsight
{
    public readonly struct Server
    {
        public readonly string Name;
        public readonly string Location;
        public readonly string OS;
        public readonly int vCPU;
        public readonly int RAM;

        public Server(string name, string location, string os, int vcpu, int ram)
        {
            Name = name;
            Location = location;
            OS = os;
            vCPU = vcpu;
            RAM = ram;
        }

    public override string ToString() => $"(Name: {Name}, Location: {Location}, Operating System: {OS}, vCPU: {vCPU}, RAM: {RAM} GB)";
    }

    public class ReadOnlyProgramming
    {
        public static void Main()
        {
            Server a = new Server("Domain Controller","Amsterdam","Centos 7.6",8,16);
            Console.WriteLine(a.ToString());
            Console.ReadKey();
        }
    }
}
    

产生的输出如下。

      (Name: Domain Controller, Location: Amsterdam, Operating System: Centos 7.6, vCPU: 8, RAM: 16 GB)
    

这里有两个重要概念。如果不将属性设为只读,我们就无法添加新属性。这样可以防止数据被修改,我们也无法更改现有属性。

当我们使用readonly 成员上下文时,我们可以选择将关键字应用于成员。但是,我们不能将其应用于类或接口成员声明。您需要记住两条规则:

  1. 静态方法或属性不能是只读的。
  2. 构造函数不能是只读的。

对于我们上面的例子来说,只读成员的一个小演示是。

      public readonly DateTime InstallDate { get; }
    

ref readonly上下文稍微复杂一些,它涉及指针和不安全代码。应用于ref 的修饰符意味着返回的引用不能被修改。任何可由ref返回的类型都可以应用 readonly 修饰符。

结论

只读编码就是保护类字段或结构中的信息。确保不允许篡改数据是我们数字世界中日益关注的问题。C# 具有帮助您编写安全应用程序的必要功能。我希望本指南对您有所帮助,并感谢您阅读它!

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据