как вы добавляете get и set для массива в c# - PullRequest
0 голосов
/ 21 апреля 2020

Я кодирую забавное c, которое вводит массив с разным годом рождения и печатает самого старого человека. Я пытаюсь добавить проверку с помощью get и set, но мой синтаксис неверен.

введите описание изображения здесь

Ответы [ 2 ]

1 голос
/ 21 апреля 2020

TL; DR

Часть объявления свойств:

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
    });
}
0 голосов
/ 21 апреля 2020

Вы можете создавать классы-оболочки над массивом и использовать метод индексатора для доступа к элементу массива. Там вы можете поместить все свои логи проверки c.

class IntData
    {

        public IntData(int size)
        {
            data = new int[size];
        }
        // Array of temperature values
        private int[] data;

        public int this[int index]
        {
            get
            {
                return data[index];
            }

            set
            {
                // Do your validation here
                if (value < 5000) 
                {
                    data[index] = value;
                }
            }
        }
    }


      static void Main(string[] args)
        {
            IntData year = new IntData(3);
            year[0] = 2000;
            year[1] = 6000; // This value won't set because of validation
            year[2] = 4000;

            Console.Read();
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...