我正在寻找改进以下代码的想法
static void Main(string[] args)
{
bool validInput1 = false;
string input1 = string.Empty;
bool validInput2 = false;
string input2 = string.Empty;
bool validFilePath = false;
string filePath = string.Empty;
try
{
Console.WriteLine("Import process started.");
while (!validFilePath)
{
Console.Write("Please enter the full path to the file you would like to import: ");
filePath = Console.ReadLine().Replace("\"","");
if (File.Exists(filePath))
validFilePath = true;
}
while (!validInput1)
{
Console.Write("Enter a valid eventID the import file: ");
input1 = Console.ReadLine();
if (ValidEventID(input1.Trim().Length))
validInput1 = true;
}
while (!validInput2)
{
Console.Write("Enter a valid import type code: ");
input2 = Console.ReadLine();
if (input2.Trim().ToUpper() == "EX" || input2.Trim().ToUpper() == "EL")
validInput2 = true;
}
var records = Utilities.ParseCSV(filePath);
var import = new Import
{
EventId = input1,
ImportType = input2
};
import.ImportEventDates(records);
Console.WriteLine("Import process completed.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error encountered");
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
预先感谢您的帮助
最佳答案
我会编写一个简单的方法来检索和验证用户输入:
public static string PromptUntilValid(string promptText, Func<string, bool> validationPredicate)
{
string input;
do
{
Console.Write(promptText);
input = Console.ReadLine();
} while (!validationPredicate(input))
return input;
}
这将允许您的代码重构如下:
...
filePath = PromptUntilValid(
"Please enter the full path to the file you would like to import: ",
s => File.Exists(s));
input1 = PromptUntilValid(
"Enter a valid eventID the import file: ",
s => ValidEventID(s.Trim().Length));
input2 = PromptUntilValid(
"Enter a valid import type code: ",
s => s.Trim().ToUpper() == "EX" || s.Trim().ToUpper() == "EL");
...
关于.net-3.5 - 需要重构建议/想法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2053514/