📜  在C#中为只读

📅  最后修改于: 2021-05-29 23:49:44             🧑  作者: Mango

在C#中,只读关键字是修饰符,可通过以下方式使用:

1.只读字段:在C#中,允许您使用只读修饰符声明一个字段。它指示对字段的分配仅是声明的一部分,或在同一类的构造函数中。只能在声明或构造函数中多次分配或重新分配此类字段。构造函数退出后未分配它们。如果将只读修饰符与值类型字段一起使用,则该字段是不可变的。并且,如果readonly修饰符与引用类型字段一起使用,则readonly修饰符可防止将该字段替换为引用类型的不同实例,此处readonly修饰符不会阻止该字段的实例数据通过读取而被修改仅限字段。在静态和实例构造函数中,允许您将只读字段作为out或ref参数传递。

例子:

// C# program to illustrate
// how to create a readonly field
using System;
  
class GFG {
  
    // readonly variables
    public readonly string str1;
    public readonly string str2;
  
    // Readonly variable
    // This variable is 
    // initialized at declaration time
    public readonly string str3 = "gfg";
  
    // The values of the readonly
    // variables are assigned
    // Using constructor
    public GFG(string a, string b)
    {
  
        str1 = a;
        str2 = b;
        Console.WriteLine("Display value of string 1 {0}, "
                         + "and string 2 {1}", str1, str2);
    }
  
    // Main method
    static public void Main()
    {
        GFG ob = new GFG("GeeksforGeeks", "GFG");
    }
}

输出:

Display value of string 1 GeeksforGeeks, and string 2 GFG

在这里,在构造函数中分配了str1和str2的值。

2.只读结构:在只读结构中,只读修饰符指示给定的结构是不可变的。创建只读结构时,有必要在其字段中使用只读修饰符,如果不执行此操作,则编译器将给出错误信息。

例子:

// C# program to illustrate how 
// to create a readonly structure
using System;
  
// Readonly structure
public readonly struct Author
{
  
    public readonly string Name { get; }
    public readonly int Article { get; }
    public readonly string Branch { get; }
    public Author(string name, int article, string branch)
    {
  
        this.Name = name;
        this.Article = article;
        this.Branch = branch;
    }
}
  
class GFG {
  
    // Main method
    static public void Main()
    {
        Author a = new Author("Rohit", 67, "CSE");
        Console.WriteLine("Author name: " + a.Name);
        Console.WriteLine("Total articles: " + a.Article);
        Console.WriteLine("Branch name: " + a.Branch);
    }
}

输出:

Author name: Rohit
Total articles: 67
Branch name: CSE

3.只读成员: C#8.0中引入了此功能。在此功能中,允许您对结构的任何成员使用只读修饰符。此只读修饰符指定不允许该成员进行修改。这比以只读方式应用整个结构更好。

例子:

// C# program to illustrate how 
// to create a readonly member
using System;
  
public struct Customer
{
  
    public string Name { get; }
    public int Price { get; }
  
    // Readonly member
    public readonly string Product { get; }
  
    public Customer(string name, string product, int price)
    {
  
        this.Name = name;
        this.Product = product;
        this.Price = price;
    }
}
  
class GFG {
  
    // Main method
    static public void Main()
    {
        Customer a = new Customer("Sumit", "Mobile Phone", 2398);
        Console.WriteLine("Customer name: " + a.Name);
        Console.WriteLine("Product: " + a.Product);
        Console.WriteLine("Price: " + a.Price);
    }
}

输出:

Customer name: Sumit
Product: Mobile Phone
Price: 2398