c# - 如何在 C# 中为数组添加 get 和 set
解决方案
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
});
}
推荐阅读
- php - SQLSTATE = 23502 出现在我部署的网站上。(通过上传 .csv)
- python - 将悬停文本添加到 Plotly 散点图线或散点图线的多种颜色
- javascript - 返回或推送字符串 Char
- export - Sqoop 导出失败并出现 NumberFormatException
- excel - 如何将多个句子中的每个单词放入Excel中的文本单元格?
- .net-core - .NET 核心中的 OpenTracing,而不依赖于特定的解决方案库
- powershell - 如何从结果对象 Invoke-WebRequest 命令中“单击”元素
- python - Selenium Webdriver with Python - 无法在使用 Selenium Web 驱动程序的 Web 应用程序中提供输入
- oracle-apex-5.1 - 从 CSV 文件加载 Apex 数据 - 表查找问题
- sql - 如何添加 CTE 以提高存储过程性能?