CSDN-Ada助手 2024-03-28 14:59 采纳率: 1.6%
浏览 10

关于结构类型中使用readonly修饰变量

该问题来自社区帖: https://bbs.csdn.net/topics/618324239.为符合问答规范, 该问题经过ChatGPT优化
```html

关于结构类型中使用readonly修饰变量

```
  • 写回答

2条回答 默认 最新

  • 专家-皆知 2024-03-28 14:59
    关注

    引自免费微信小程序:皆我百晓生

    在C#编程语言中,readonly关键字用于修饰可变成员(属性、字段、方法)使其只读(readonly)。当我们声明一个结构类型(struct),其内部的字段(member)都被声明为readonly时,这些字段的所有值只能从外部通过赋值操作获取,而且一旦设置或修改后,就不能更改。

    以下是多个示例来展示如何在C#中实现只读结构类型:

    1. 声明一个结构类型并初始化为只读:
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    
        public readonly Person State = new Person();
    }
    

    在这个例子中,我们首先声明了一个名为Person的结构类型,并为其中的两个字段NameAge分别设置了初始值。然后,我们指定了State成员为Person类型的构造函数参数,即一个默认的实例。这样,State成员就是Person类的一个静态局部变量,只允许通过构造函数进行初始化。

    1. 使用readonly关键字添加成员到不可变数组:
    public struct Stack<T> : IEnumerable<T>
    {
        private readonly T[] items;
    
        public Stack(int capacity)
        {
            this.items = new T[capacity];
        }
    
        public void Push(T item)
        {
            Array.Resize(ref this.items, this.items.Length + 1);
            items[this.items.Length - 1] = item;
        }
    
        public T Pop()
        {
            if (this.isEmpty())
                throw new InvalidOperationException("Stack is empty");
    
            T item = items[this.items.Length - 1];
            Array.Resize(ref this.items, this.items.Length - 1);
            items[this.items.Length - 2] = null;
            return item;
        }
    
        public bool IsEmpty()
        {
            return this.items == null || this.items.Length == 0;
        }
    
        public IEnumerator<T> GetEnumerator()
        {
            for (int i = 0; i < this.items.Length; i++)
                yield return this.items[i];
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    
    // 示例用法
    Stack<int> stack = new Stack<int>(5);
    stack.Push(1); // 声明push方法为非只读
    stack.Push(2); // 修改了push方法
    stack.Pop(); // 按照序列遍历,移除元素2
    
    Console.WriteLine(stack.IsEmpty()); // 输出:true
    Console.WriteLine(stack.Count); // 输出:2
    

    在这个示例中,我们创建了一个结构类型Stack<int>,其中包含一个不可变整数数组items。我们为其提供了两个公共成员Push()Pop(),这两个方法都是只读的,即使在扩展队列时(在IsEmpty()方法中),我们也禁止改变items数组。Push()方法仅将元素添加到队列头部,而Pop()方法则删除并返回队列尾部的第一个元素。

    1. 使用readonly关键字添加成员到接口:
    public interface IFoo<T>
    {
        T This { get; }
    }
    
    public class Bar : IFoo<int>
    {
        readonly int x;
    
        public Bar(int x)
        {
            this.x = x;
        }
    
        public int This => this.x;
    }
    
    public class Main
    {
        public static void Main(string[] args)
        {
            IFoo<int> foo = new Bar(5);
    
            Console.WriteLine(fooThis(5)); // 输出:5
            Console.WriteLine(fooThis(6)); // 输出:Invalid access to non-static field or property 'Bar.this' of type 'Bar'.
        }
    }
    

    在这个示例中,我们创建了一个IFoo<int>接口,并定义了一个名为Bar的子接口。我们为Bar接口中的成员This添加了readonly关键字,这意味着只有在调用foo.This方法时才能访问其非静态字段x,否则会抛出异常。Main方法创建了一个Bar对象foo,并尝试对foo.这个不可见的字段进行访问,由于它是readonly的,所以编译器会抛出一个Invalid access to non-static field or property 'Bar.this' of type 'Bar'.'错误。

    总结: 通过使用readonly关键字,我们可以限制成员的行为和访问权限,确保仅读取、更新或设置结构类型内部的只读字段。这有助于保持数据的一致性和完整性,防止未授权的访问或修改导致意外的结果。在实际应用中,readonly关键字通常与不可变集合(如数组、链表等)结合使用,以便更好地管理数据的引用状态。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 3月28日

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题