Is there idiomatic C# equivalent to C's comma operator?

前端 未结 7 1943
死守一世寂寞
死守一世寂寞 2020-12-14 07:18

I\'m using some functional stuff in C# and keep getting stuck on the fact that List.Add doesn\'t return the updated list.

In general, I\'d like to call

相关标签:
7条回答
  • 2020-12-14 08:14

    I thought it would be interesting to make a version of my wrapper class answer that doesn't require you write the wrapper methods.

    public class FList<T> : List<T>
    {
        public FList<T> Do(string method, params object[] args)
        {
            var methodInfo = GetType().GetMethod(method);
    
            if (methodInfo == null)
                throw new InvalidOperationException("I have no " + method + " method.");
    
            if (methodInfo.ReturnType != typeof(void))
                throw new InvalidOperationException("I'm only meant for void methods.");
    
            methodInfo.Invoke(this, args);
            return this;
        }
    }
    
    {
        var list = new FList<string>();
    
        list.Do("Add", "foo")
            .Do("Add", "remove me")
            .Do("Add", "bar")
            .Do("RemoveAt", 1)
            .Do("Insert", 1, "replacement");
    
        foreach (var item in list)
            Console.WriteLine(item);    
    }
    

    Output:

    foo 
    replacement 
    bar
    

    EDIT

    You can slim down the syntax by exploiting C# indexed properties.

    Simply add this method:

    public FList<T> this[string method, params object[] args]
    {
        get { return Do(method, args); }
    }
    

    And the call now looks like:

    list = list["Add", "foo"]
               ["Add", "remove me"]
               ["Add", "bar"]
               ["RemoveAt", 1]
               ["Insert", 1, "replacement"];
    

    With the linebreaks being optional, of course.

    Just a bit of fun hacking the syntax.

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