Modifying parameter values before sending to Base constructor

前端 未结 7 558
借酒劲吻你
借酒劲吻你 2021-01-07 16:26

The title may be a bit ambiguous, but I couldn\'t think of a better way to word this.

I realize that I can not call a derived constructor prior to calling a base con

7条回答
  •  旧时难觅i
    2021-01-07 16:52

    One hack to put arbitrary logic in base() clause without introducing a separate static method is to use a lambda or anonymous delegate. The expression inside base() is in scope of all constructor parameters, so you can freely use them inside the lambda. E.g. (let's say this is C# 2.0, so there's no LINQ to write a single-liner for the same thing):

    class Base
    {
        public Base(int[] xs) {}
    }
    
    class Derived : Base
    {
        public Derived(int first, int last)
            : base(
                ((Func)delegate
                {
                    List xs = new List();
                    for (int x = first; x < last; ++x)
                    {
                        xs.Add(x);
                    }
                    return xs.ToArray();
                })())
        {
        }
    }
    

    However, I would strongly advise against using this in practice, because from readability point of view this is really horrible. With a static method you'll need to explicitly pass constructor arguments to it, but it's not like you normally have more than 3-4 of those.

提交回复
热议问题