What's so great about Func<> delegate?

前端 未结 6 634
迷失自我
迷失自我 2020-12-12 13:57

Sorry if this is basic but I was trying to pick up on .Net 3.5.

Question: Is there anything great about Func<> and it\'s 5 overloads? From the looks of it, I can

6条回答
  •  再見小時候
    2020-12-12 14:36

    One thing I like about delegates is that they let me declare methods within methods like so, this is handy when you want to reuse a piece of code but you only need it within that method. Since the purpose here is to limit the scope as much as possible Func<> comes in handy.

    For example:

    string FormatName(string pFirstName, string pLastName) {
        Func MakeFirstUpper = (pText) => {
            return pText.Substring(0,1).ToUpper() + pText.Substring(1);
        };
    
        return MakeFirstUpper(pFirstName) + " " + MakeFirstUpper(pLastName);
    }
    

    It's even easier and more handy when you can use inference, which you can if you create a helper function like so:

    Func Lambda(Func pFunc) {
        return pFunc;
    }
    

    Now I can rewrite my function without the Func<>:

    string FormatName(string pFirstName, string pLastName) {
        var MakeFirstUpper = Lambda((string pText) => {
            return pText.Substring(0,1).ToUpper() + pText.Substring(1);
        });
    
        return MakeFirstUpper(pFirstName) + " " + MakeFirstUpper(pLastName);
    }
    

    Here's the code to test the method:

    Console.WriteLine(FormatName("luis", "perez"));
    

提交回复
热议问题