第一次使用lambda.如果可能的话,希望把更多的代码内联

本文关键字:希望 代码 lambda 如果 第一次 | 更新日期: 2023-09-27 18:18:05

我目前正试图教我自己如何使用lambda表达式(真的很喜欢他们的样子)

在我的win表单上,我有2个用于浏览目录的按钮,然后将用户选择的目录放在相应的文本框中。这是我目前掌握的信息。

在setDirectory事件中,是否有任何方法可以将按钮检查内联?我真的希望清理setDirectory事件中的代码。

        private void setDirectory_Click(object sender, EventArgs e)
        {
           Button dirButton = sender as Button;
           TextBox dirTextBox;
           if (dirButton.Name == fromDirButton.Name)
               dirTextBox = fromTextBox;
           else
               dirTextBox = toTextBox;
           Func<string> setDirectory = SetDirectory();
           fromTextBox.Invoke((MethodInvoker)(() => { dirTextBox.Text = setDirectory(); }));
        }
        private static Func<string> SetDirectory()
        {
           using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
           {
               folderBrowserDialog.Description = "Select Path";
               folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;
               folderBrowserDialog.ShowDialog();
               return () => folderBrowserDialog.SelectedPath != "" ? folderBrowserDialog.SelectedPath : "";
           }
        }

第一次使用lambda.如果可能的话,希望把更多的代码内联

希望在可能的情况下嵌入更多代码

为什么?这看起来不像是正确使用Lambda表达式

你的问题应该是:

何时使用Lambda表达式,何时不使用?

Lambda表达式不能取代传统的编码,如对话框等。它们提供了一种以更实用的方式表达正在完成的工作的方法。

var net30PastDueInvoices = 
    invoiceRepository.GetInvoicesFor(currentClient)
        .Where(f => 30 < DateTime.Today.AddDays(-f.InvoiceDate));

或者甚至处理成迭代:

var items = repository.GetList().ForEach(i => {
        // Process items here.
        // Notice that the code processed here is located in a foreach loop
        // especially for the given purpose within an anonymous method.
        // Should you need to perform this operation over and over again,
        // you should extract this to a proper method and describe what it 
        // does in its name.
    });

你尝试使用Lambda表达式的方式是非常不鼓励的,因为它只会增加代码的复杂性。

总之,Lambda Expression非常实用,可以用函数式的方式表达业务规则等。除此之外,保持简单,愚蠢(KISS)!

免责声明

我不是说你笨,在这里。点击链接了解更多。

你的使用方式并不适合Lambda, Lambda在Linq &泛型使得它非常容易使用。一个例子:

List<string> collection = new List<string>();
if(!collection.Any())
     // Collection isn't null.
var quantity = collection.Count(c => c > 5);
如您所见,Lambda用管道传递数据,这是有意义的。它变得富有表现力,而不是模糊不清。

在可能使用Lambda的区域,使用更传统的实现可能会更好。原因很简单,它变得越来越复杂,表达能力越来越弱。这使得代码更难维护和重构,简单通常是最好的方法。

我建议在适当的环境中尝试学习Lambda,而不是为了使用它们