是否有可能创建构造扩展法?怎么样? [英] Is it possible to create constructor-extension-method ? how?
问题描述
是否有可能增加一个构造函数扩展方法?我想补充一个List< T>构造成接收字节特定量出一个给定的部分填充的缓冲器的(不仅复制相关字节等的开销):
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 (without the overhead of copying only the relevant bytes and so on):
...
public static List<T>(this List<T> l, T[] a, int n)
{
for (int i = 0; i < n; i++)
l.Add(a[i]);
}
...
所以用法是:
so the usage would be:
List<byte> some_list = new List<byte>(my_byte_array,number_of_bytes);
我已经添加了一个扩展的AddRange方法:
I've already added an AddRange extension method:
public static void AddRange<T>(this List<T> l, T[] a, int n)
{
for (int i = 0; i < n; i++)
l.Add(a[i]);
}
我想这样做,作为构造了。是否可以 ?如果是的话 - 如何
I want to do it as a constructor too. Is it possible ? if yes - how ?
推荐答案
没有,但是如果你改变了你的的AddRange
签名返回列表实例,那么你至少可以做
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.
这篇关于是否有可能创建构造扩展法?怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!