```html
关于结构类型中使用readonly修饰变量
```关于结构类型中使用readonly修饰变量
```引自免费微信小程序:皆我百晓生
在C#编程语言中,readonly
关键字用于修饰可变成员(属性、字段、方法)使其只读(readonly)。当我们声明一个结构类型(struct),其内部的字段(member)都被声明为readonly时,这些字段的所有值只能从外部通过赋值操作获取,而且一旦设置或修改后,就不能更改。
以下是多个示例来展示如何在C#中实现只读结构类型:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public readonly Person State = new Person();
}
在这个例子中,我们首先声明了一个名为Person
的结构类型,并为其中的两个字段Name
和Age
分别设置了初始值。然后,我们指定了State
成员为Person
类型的构造函数参数,即一个默认的实例。这样,State
成员就是Person
类的一个静态局部变量,只允许通过构造函数进行初始化。
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()
方法则删除并返回队列尾部的第一个元素。
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
关键字通常与不可变集合(如数组、链表等)结合使用,以便更好地管理数据的引用状态。