More fluent C# / .NET

后端 未结 21 1183
名媛妹妹
名媛妹妹 2020-12-23 22:51

A co-worker of mine came up with this and I wonder what others think? Personally, I find it interesting but wonder if it is too big a departure? Code examples below. Extensi

相关标签:
21条回答
  • 2020-12-23 23:39

    This is a perfect learning case on how to make something more complicated than it needs to be.

    The first version is clear and requires no extra knowledge beyond normal language contructs.

    0 讨论(0)
  • 2020-12-23 23:40

    The original is more readable.

    The simplest API change would be to make the object returned by FindControl() a Builder-esque thing (where all the set methods return 'this'):

    Page.FindControl("LocationDropDownList")
        .setVisible(true)
        .setSelectedValue(isAdmin ? "111" : "123");
    
    0 讨论(0)
  • 2020-12-23 23:41

    It's an interesting use of extensions, and I appreciate it on that merit alone. I'm not sure I'd use it, but if your team likes it, then by all means, use it.

    0 讨论(0)
  • 2020-12-23 23:43

    I see no advantage to this besides being confusing to the reader. With respect to my fellow answerer, I would like to know on what planet this is more readable. As far as I can tell, the first version has more or less perfect readability, whereas this is fairly readable, but makes the reader wonder whether there's some strange magic happening within With and WithIf.

    Compared to the first version, it's longer, harder to type, less obvious, and less performant.

    0 讨论(0)
  • 2020-12-23 23:44

    They're just different coding styles, what do you mean by "too big a departure"? Departure from what? From what you're used to? Only you can decide that. I will say that VB's With block has done more harm than good to code readability, and I would not try to replicate the behavior in C#, but that's just my preference.

    I pretty much always use this for FindControl (yeah, strongly typed to RepeaterItem, it doesn't have to be, but that's the only thing I ever use it for anyway):

    public static T FindControl<T>(this RepeaterItem item, string id) 
    {
        return item.FindControl(id) as T;
    }
    

    And invoke it like so:

    Literal myLiteral = e.Item.FindControl<Literal>("myLiteral");
    
    0 讨论(0)
  • 2020-12-23 23:44

    I say stick with the first version without the extension methods or lamba expressions. These are relatively new concepts so not many developers will have a handle on them yet outside their use in data retrieval/manipulation from a database. If you use them you may have a hit on maintenance cost. It is nice to say "read up if this is Greek to you"; but in real-life that may be the best approach.

    0 讨论(0)
提交回复
热议问题