【C#基础】属性

访问属性时,其行为类似于字段。不同的是属性通过访问器实现;访问器用于定义访问属性或为属性赋值时执行的语句。

属性语法

1.赋初始值

public class Person
{
    public string FirstName { get; set; } = string.Empty;
}

2.可为 getter 或 setter 使用 expression-bodied
3.set 访问器始终有一个名为 value 的参数。 get 访问器必须返回一个值,该值可转换为该属性的类型

方案

验证

可以在set访问器编写规则代码

public class Person
{
    public string FirstName
    {
        get => firstName;
        set => firstName = (!string.IsNullOrWhiteSpace(value)) ? value : throw new ArgumentException("First name must not be blank");
    }
    private string firstName;
}

只读

1.在单个访问器上放置的任何访问修饰符都必须比属性定义上的访问修饰符提供更严格的限制
2.只读访问器({get;})只能在构造函数或属性初始化表达式中设置属性。

public class Measurements
{
    public ICollection<DataPoint> points { get; } = new List<DataPoint>();
}

计算属性

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName => $"{FirstName} {LastName}";//只读属性
}

缓存的计算属性

public class Person
{
    private string firstName;
    public string FirstName
    {
        get => firstName;
        set
        {
            firstName = value;
            fullName = null;
        }
    }

    private string lastName;
    public string LastName
    {
        get => lastName;
        set
        {
            lastName = value;
            fullName = null;
        }
    }

    private string fullName;
    public string FullName
    {
        get
        {
            if (fullName == null)
                fullName = $"{FirstName} {LastName}";
            return fullName;
        }
    }
}

将特性附加到属性

public class Person
{
    [field:NonSerialized]
    public int Id { get; set; }
}

实现 INotifyPropertyChanged

public class Person : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string firstName;
        public string FirstName
        {
            get => firstName;
            set
            {
                if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("First name must not be blank");
                if (value != firstName)
                {
                    firstName = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FirstName)));
                }
            }
        }

限制访问器可访问性

属性或索引器的 get 和 set 部分称为访问器。默认访问器同属性或索引具有相同的访问级别

对访问器的访问修饰符的限制

1.不能对接口或显式接口成员实现使用访问器修饰符
2.仅当属性或索引器同时具有 set 和 get 访问器时,才能使用访问器修饰符。 这种情况下,只允许对其中一个访问器使用修饰符。
3.重写属性和索引器时,若一个访问器有方法体,另一个也必须有。
4.访问器的可访问性级别必须比属性或索引器本身的可访问性级别具有更严格的限制。
5.抽象属性或索引器的访问器不能加修饰符

posted @ 2022-04-19 21:21  是卡卡罗特啊  阅读(37)  评论(0编辑  收藏  举报