c# - C#验证类属性中的整数用户输入
问题描述
今天是个好日子。令我感到羞耻的是,不明白如何制作它。我有一个像这样的课程:
public class Worker
{
public int ID { get; set; }
}
和带有工人列表的数据类。有一种方法可以使用它:
public Department GetWorkerByID (int id)
{
foreach (Worker worker in Workers)
{
if (worker.ID == id)
return worker;
}
return null;
{
问题是我需要让用户能够通过 ID 号从列表中选择当前工作人员,并且我希望程序处理无效输入,如随机符号、字母等,并检查输入 ID 是否存在。通常我为此使用布尔属性:
string input = Console.ReadLine();
bool isInt = int.TryParse(input, out _);
等等。但是如果使用类属性,它不会像我预期的那样工作,当我尝试这样做时:
while (!isInt && Data.GetWorkerByID(int.Parse(input)) == null)
{
Console.Write("Wrong input. Try again: ");
input = Console.ReadLine();
}
它不起作用,向我抛出 ID 号无效格式的异常或传递数字,而不是尝试获取不存在的 worker 实例。欢迎任何建议。
解决方案
尝试做这样的事情:
C#:
public Worker TryGetWorker()
{
string input = Console.ReadLine();
int index = -1;
bool isInt = int.TryParse(input,out index);
Worker worker = Data.GetWorkerByID(index);
if (!isInt || worker == null)
{
Console.Write("Wrong input. Try again: ");
return TryGetWorker();
}
else
return worker;
}
推荐阅读
- android - 将图像展开/折叠到图像列表中
- reactjs - 如何在我的 Modal 上使用键(从列表项键中定义)作为道具
- c# - 应用程序不会通过 docker build 从 github 检索秘密
- python - Jinja2得到语法错误Python生成器
- python - Keras:`image_dataset_from_directory` 中的标签的 one-hot
- typescript - 表单切片缩减器中的复选框处理
- python - 如何将系列字典转换为熊猫中的单独列
- javascript - 检查nodejs中的星期几是否在星期一和星期日之间
- javascript - 在这个例子中,传递给 promise 的回调函数的参数是什么?
- android - androidx.media2.player.MediaPlayer 结合两种声音