gpt4 book ai didi

c# - 减少 C# 中重复代码的最佳方法 - 需要创建 DateTime 转换函数

转载 作者:行者123 更新时间:2023-12-02 02:18:03 25 4
gpt4 key购买 nike

我用 C# 编写了以下代码,并希望防止每次都重新编写 try 语句。

  1. 这是在使用多个对象时减少重复代码的最佳方法吗?创建一次代码函数并且该函数编写正确吗?

  2. 我无法在范围内使用“GoTo”,有人可以请问为什么以及如何解决这个问题吗?

Console.WriteLine("Enter DOB for member {0} - yyyy - mm - dd format", memberName);
//enter DOB for object, also create DateTime struct instance below,"d" is just a reference
DateTime d = new DateTime();
string dob = Console.ReadLine();
//pass string to convert to Date tinme
try
{
d = Convert.ToDateTime(dob);
}
catch (Exception ex)
{
Console.WriteLine("Exception in date. This record cannot be stored");
goto again1;
}

Console.WriteLine("Enter Date of Order {0} - yyyy - mm - dd format", memberName);
//enter DOB for object, also create DateTime struct instance below,"dor" is just a reference
DateTime dor = new DateTime();
string dorder = Console.ReadLine();
//pass string to convert to Date tinme
try
{
dor = Convert.ToDateTime(dorder);
}
catch (Exception ex)
{
Console.WriteLine("Exception in date. This record cannot be stored");
goto again1;
}

//my attempted reduce code local function
DateTime StringToDateConvert (DateTime structref, string dateoforder)
{
try
{
structref = Convert.ToDateTime(dateoforder);
}
catch (Exception ex)
{
Console.WriteLine("Exception in date. This record cannot be stored");
goto again1;
}
return;
}

最佳答案

不,这不是将字符串转换为 DateTime 的最佳方式,因为已经有 DateTime.TryParse这避免了使用异常来处理常见情况:

bool isValidBirthDate = DateTime.TryParse(Console.ReadLine(), out DateTime dob);

因此,在这种情况下,由于您想重复询问用户的出生日期,请使用循环:

do
{
Console.WriteLine("Enter Date of Order {0} - yyyy - mm - dd format", memberName);
} while (!DateTime.TryParse(Console.ReadLine(), out DateTime dob));

// now you have a valid DateTime in dob

如果您想提供无法自动工作的特定格式,请查看 DateTime.TryParseExact并学习how format-specifier work .

关于goto:只是不要使用它们。使用循环、方法等,你根本不需要它们。

关于c# - 减少 C# 中重复代码的最佳方法 - 需要创建 DateTime 转换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66882976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com