是否可以创建构造函数-扩展-方法? 如何创建?

是否可以添加构造函数扩展方法?

示例用例

我想添加一个 List < T > 构造函数,从给定的部分填充缓冲区中接收特定数量的字节(不需要复制相关字节等等的开销) :

...
public static List<T>(this List<T> l, T[] a, int n)
{
for (int i = 0; i < n; i++)
l.Add(a[i]);
}
...

所以用法是:

List<byte> some_list = new List<byte>(my_byte_array,number_of_bytes);

我已经添加了一个 AddRange 扩展方法:

public static void AddRange<T>(this List<T> l, T[] a, int n)
{
for (int i = 0; i < n; i++)
l.Add(a[i]);
}

我也想作为一个构造函数来做。这可能吗? 如果可能-怎么做?

39074 次浏览

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.

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.

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.

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);
}
}

Yes-ish but no?

MyClass{
public MyClass(params){ //do stuff };
public MyClass MyConstructorAddOn(moreParams){ //do more stuff; return this;}
}

then call this way:

MyClass(params).MyConstructorAddOn(moreParams);

It works a bit like an extension method. Although NOT a constructor, it can be used as a daisy chain on a constructor to do more stuff outside of the constructor immediately. I believe this is called fluent interfaces.