C# 我能把它转换成lambda语句吗?
我想知道是否有可能将这个while循环转换成lambda语句?我知道如果它是for或foreach循环是可能的,但它是一个普通的while循环:C# 我能把它转换成lambda语句吗?,c#,lambda,while-loop,C#,Lambda,While Loop,我想知道是否有可能将这个while循环转换成lambda语句?我知道如果它是for或foreach循环是可能的,但它是一个普通的while循环: while (path.Substring(path.Length - 4) != ".txt" || path.Substring(path.Length - 4) != ".xml") { Console.WriteLine("File not a .txt or .xml extension! Enter the file name:")
while (path.Substring(path.Length - 4) != ".txt" || path.Substring(path.Length - 4) != ".xml")
{
Console.WriteLine("File not a .txt or .xml extension! Enter the file name:");
path = Console.ReadLine();
}
如果可能的话,如何将这个循环转换成这样一个lambda语句?如果您想这样做是为了学习和学术目的:
Func<string[], string> getFile = (validExtensions) =>
{
string path = "";
while (!validExtensions.Contains(Path.GetExtension(path)))
{
Console.WriteLine("File not a .txt or .xml extension! Enter the file name:");
path = Console.ReadLine();
}
return path;
};
string path = getFile.Invoke(new string[]{ ".txt", ".xml" });
鉴于对该问题的评论表明,这并不是关于lambdas,而是关于最小化代码,下面是一些避免代码重复的小建议:
string[] validExtensions = { ".txt", ".xml" };
do
{
Console.WriteLine("Enter the file name:");
path = Console.ReadLine();
if (!validExtensions.Contains(Path.GetExtension(path)))
{
Console.Write("File not a .txt or .xml extension! ");
path = null;
}
}
while (path == null);
检查另一个扩展只需要将扩展添加到数组中,而不需要复制代码来确定扩展。字符串“输入文件名:“
只需出现一次,即使您希望第一次提示的消息略有不同。读取一行的代码也只需出现一次
就个人而言,我想说的是,您的重复非常小,现在还没有必要避免它,但是您可能会发现这很有用,例如,如果您需要再允许三个扩展,或者从某个其他位置读取单个函数调用是不够的
一些补充意见:
可以返回Console.ReadLine()
。就像你问题中的代码一样,这个版本不能正确处理这个问题null
- 文件扩展名中的大小写通常被忽略。是否确实要拒绝将
作为文件扩展名“.TXT”
- 您的
条件while
永远不会为假。它可能是真的,也可能抛出异常,但循环永远不会正常终止path.Substring(path.Length-4)!=“.txt”| | path.Substring(path.Length-4)!=“.xml”
newaction(()=>{while(…){…})(代码>。这是完全无用的,但你似乎没有要求一些有用的东西。你能详细解释一下吗?@ChrisDixon不,那部分很有道理。只要用户继续输入无效的文件名,程序就会提示输入有效的文件名。请查看Path.GetExtension(string Path)
这不会编译。即使你把它改成可以编译的东西,它也没用,这就是为什么我在问题上放了类似的注释,而不是答案。如果你把它放在匿名方法的局部变量中,你会如何处理用户输入的路径?我不知道,返回它?
string[] validExtensions = { ".txt", ".xml" };
do
{
Console.WriteLine("Enter the file name:");
path = Console.ReadLine();
if (!validExtensions.Contains(Path.GetExtension(path)))
{
Console.Write("File not a .txt or .xml extension! ");
path = null;
}
}
while (path == null);