C# 类的属性设置器 (set) 接收参数的语法如下:

public class MyClass
{
    private int myProperty;

    public int MyProperty
    {
        get { return myProperty; } 
        set { myProperty = value; }
    }
}

在上面的示例中,'MyProperty' 是一个公共属性,它具有一个设置器 (set) 和一个获取器 (get)。设置器用于设置属性的值,获取器用于获取属性的值。

在设置器 (set) 中,使用关键字'value' 来表示传递给属性设置器的参数。在上面的示例中,我们将传递给 'MyProperty' 设置器的值存储在 'myProperty' 字段中。

当使用属性设置器 (set) 时,可以执行一些验证逻辑来确保传递给属性的值是有效的。例如,可以检查传递的值是否满足特定的条件,如果不满足条件,则可以抛出异常。

以下是一个具有验证逻辑的示例:

public class MyClass
{
    private int myProperty;

    public int MyProperty
    {
        get { return myProperty; } 
        set
        {
            if (value < 0)
            {
                throw new ArgumentException('Value must be greater than or equal to zero');
            }
            myProperty = value;
        }
    }
}

在上面的示例中,如果传递给 'MyProperty' 设置器的值小于 0,则会抛出一个 'ArgumentException' 异常。

C# 类属性 set 接收参数详解

原文地址: https://www.cveoy.top/t/topic/l76Q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录