开发者

IDictionary AddAndReturn extension for fluent interface

开发者 https://www.devze.com 2023-04-04 04:18 出处:网络
What\'s nice about jQuery, which is a great JavaScript library, is to be able to get the element you are working on as return value. Here is an example of what I am referring to:

What's nice about jQuery, which is a great JavaScript library, is to be able to get the element you are working on as return value. Here is an example of what I am referring to:

$(function() { 
    $("#poo").css("clear", "both").css("margin", "10px");
});

I would like to implement the same for the C# IDictionary interface so that I can write code as follows:

IDictionary<string, string> myDictionary = 
    new Dictionary<string, string>().
        Add("key1", "value1").
       开发者_StackOverflow社区 Add("key2", "value2").
        Add("key3", "value3");

So I have created an extension method as below for IDictionary:

public static IDictionary<string, string> AddAndReturn(this IDictionary<string, string> dictionary, string key, string value) {
    dictionary.Add(key, value);
    return dictionary;
}

And now I am able to use it like:

IDictionary<string, string> poo = 
    new Dictionary<string,string>().
        AddAndReturn("key1", "value1").
        AddAndReturn("key2", "value2").
        AddAndReturn("key3", "value3");

I wonder if I am following the right path here.

Is what I am doing a poor man's fluent interface implementation or totally unrelated to that?

Is there any known case for this implementation in C#?


While your implementation pattern is correct (and a common one at that,) your use case is probably not the best choice. Object Collection initializers work for dictionary types too:

var poo =  new Dictionary<string,string> {
        { "key1", "value1" },
        { "key2", "value2" },
        { "key3", "value3" }, // this is permissible
};

The compiler magically turns this into Add(string, string) calls. Btw, the apparently erroneous comma after the last pair is deliberate. The compiler allows this so you can simplify logic in code generators such as T4.


Is there any known case for this implementation in C#?

Regarding this, I would like to add that the StringBuilder.Append() method returns the StringBuilder, making the method chainable, such as:

sb.Append("a").Append("b"). Append("c")

But there aren't many other examples like that in .NET.

0

精彩评论

暂无评论...
验证码 换一张
取 消