减少C#中重复代码的最佳方法-需要为DateTime转换创建函数
c#
我已经用 C# 编写了以下代码,并希望防止每次都重新编写 try 语句。
-
这是在使用多个对象时减少重复代码的最佳方法,创建一次代码函数并且函数编写正确吗?
-
我不能在范围内使用“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并了解format-specifier 如何工作。
关于gotos:只是不要使用它们。使用循环、方法等,您根本不需要它们。