c#

C#属性与索引器如何实现只读

小樊
82
2024-10-24 01:20:22
栏目: 编程语言

在C#中,可以通过将属性的get访问器设为publicreadonly,或者为索引器设置readonly属性来实现只读。

  1. 属性实现只读:
public class MyClass
{
    private int _myProperty;

    public MyClass(int myProperty)
    {
        _myProperty = myProperty;
    }

    // 只读的 get 访问器
    public int MyProperty
    {
        get { return _myProperty; }
    }
}

在这个例子中,MyProperty属性被设置为只读,因为它具有一个publicget访问器,但没有set访问器。这意味着您可以在类的外部访问MyProperty,但不能修改它的值。

  1. 索引器实现只读:
public class MyClass
{
    private int[] _myArray = new int[] { 1, 2, 3 };

    // 只读的 get 访问器
    public int this[int index]
    {
        get
        {
            if (index >= 0 && index < _myArray.Length)
            {
                return _myArray[index];
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(index));
            }
        }
    }
}

在这个例子中,我们为索引器定义了一个readonly属性。这意味着您可以在类的外部访问索引器,但不能修改它的值。请注意,在这种情况下,索引器仍然具有get访问器,但没有set访问器。

0
看了该问题的人还看了