Is it possible to create constructor-extension-method ? how?

后端 未结 4 527
半阙折子戏
半阙折子戏 2020-12-30 18:22

Is it possible to add a constructor extension method ? I want to add a List< T > constructor to receive specific amount of bytes out of a given partially filled buffer (w

相关标签:
4条回答
  • 2020-12-30 18:37

    In a word - no. Take a look at this for some explanation.

    They were cut from the C# 3 feature list, then they were cut from the C# 4 feature list, and we can only hope that they could make the C# 5 features, but I'm not very optimistic.

    0 讨论(0)
  • 2020-12-30 18:42

    No, but if you changed your AddRange signature to return the list instance, then you could at least do

    var list = new List<int>().AddRange(array, n);
    

    which imho is probably clearer than overloading the constructor anyway.

    0 讨论(0)
  • 2020-12-30 18:49

    I know this is a bump, just wanted to point out you can inherit the List class and do something like this:

    class List<T> : System.Collections.Generic.List<T>
        {
            public List(T[] a, int n)
                : base()
            {
                    AddRange(a, n);
            }
        }
    
    0 讨论(0)
  • 2020-12-30 18:50

    SWeko's answer is basically correct, though of course the article he links to is about extension properties rather than extension constructors.

    We also did a rough design for extension constructors at the same time as we did extension properties; they would be a nice syntactic sugar for the factory pattern. However, they never got past the design stage; the feature, though nice, is not really necessary and does not enable any awesome new scenarios.

    If you have a really awesome problem that extension constructors would solve, I'd be happy to hear more details. The more real-world feedback we get, the better we are able to evaluate the relative merits of the hundreds of different feature suggestions we get every year.

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