首页 > 解决方案 > 如何在 C# 中为数组添加 get 和 set

问题描述

我正在编写一个函数,该函数输入一个具有不同出生年份的数组并打印出最年长的人。我正在尝试使用 get 和 set 添加验证,但我的语法错误。

在此处输入图像描述

标签: c#

解决方案


TL;博士

属性声明部分:

public class Employee
{
    private string _fullName;
    private int _yearIn;

    public string FullName
    {
        get => _fullName;
        set
        {
            if (!string.IsNullOrEmpty(value))
            {
                _fullName = value;
            }
        }

    }

    public int YearIn
    {
        get => _yearIn;
        set
        {
            if (value > 0 && value <= 2020)
            {
                _yearIn = YearIn;
            }
        }
    }
}

还有一个用法:

var employees = new List<Employee>();
for (int i = 0; i < 3; i++)
{
    Console.WriteLine("Enter Name:");
    string name = Console.ReadLine();

    Console.WriteLine("Enter Year:");
    int yearIn = Convert.ToInt32(Console.ReadLine());

    employees.Add(new Employee
    {
        FullName = name,
        YearIn = yearIn
    });
}

更新
您可以以不同的方式执行相同的操作:

public class Employee
{
    private string _fullName;
    private int _yearIn;

    public bool IsNameValid { get; set; }
    public bool IsYearValid { get; set; }

    public string FullName
    {
        get => _fullName;
        set
        {
            _fullName = value;
            IsNameValid = string.IsNullOrEmpty(value);
        }

    }

    public int YearIn
    {
        get => _yearIn;
        set
        {
            _yearIn = value;
            IsYearValid = (value < 0) || (value > 2020);
        }
    }
}

然后:

Console.WriteLine($"Employee name is: {employees[i].IsNameValid}");
Console.WriteLine($"Employee year is: {employees[i].IsYearValid}");

更新 2
最后一个替代版本是您可以使用验证属性

public class Employee
{
    [Required]
    [Range(0, 2020)]
    public int YearIn { get; set; }

    [Required]
    [StringLength(50)]
    public string FullName { get; set; }
}

之后:

var empl = new Employee{ YearIn =  yearIn, FullName = name};

var context = new ValidationContext(empl, serviceProvider: null, items: null);
var results = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(empl, context, results, true);
Console.WriteLine($"Is model valid: {isValid}");

if (isValid)
{
    employees.Add(new Employee
    {
        FullName = name,
        YearIn   = yearIn
    });
}

推荐阅读