What's so great about Func<> delegate?

前端 未结 6 623
迷失自我
迷失自我 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:45

    Decoupling dependencies and unholy tie-ups is one singular thing that makes it great. Everything else one can debate and claim to be doable in some home-grown way.

    I've been refactoring slightly more complex system with an old and heavy lib and got blocked on not being able to break compile time dependency - because of the named delegate lurking on "the other side". All assembly loading and reflection didn't help - compiler would refuse to just cast a delegate() {...} to object and whatever you do to pacify it would fail on the other side.

    Delegate type comparison which is structural at compile time turns nominal after that (loading, invoking). That may seem OK while you are thinking in terms of "my darling lib is going to be used forever and by everyone" but it doesn't scale to even slightly more complex systems. Fun<> templates bring a degree of structural equivalence back into the world of nominal typing . That's the aspect you can't achieve by rolling out your own.

    Example - converting:

    class Session ( 
        public delegate string CleanBody();    // tying you up and you don't see it :-)
        public static void Execute(string name, string q, CleanBody body) ... 
    

    to:

        public static void Execute(string name, string q, Func body)
    

    Allows completely independent code to do reflection invocation like:

    Type type = Type.GetType("Bla.Session, FooSessionDll", true); 
    MethodInfo methodInfo = type.GetMethod("Execute"); 
    
    Func d = delegate() { .....}  // see Ma - no tie-ups :-)
    Object [] params = { "foo", "bar", d};
    methodInfo.Invoke("Trial Execution :-)", params);
    

    Existing code doesn't notice the difference, new code doesn't get dependence - peace on Earth :-)

提交回复
热议问题