在泛型类型的构造函数中使用C#params关键字 [英] Using C# params keyword in a constructor of generic types
问题描述
我在C#泛型类有2个构造函数:
I have a generic class in C# with 2 constructors:
public Houses(params T[] InitialiseElements)
{}
public Houses(int Num, T DefaultValue)
{}
使用INT作为泛型类型构造一个对象,并传递两个整数作为参数会导致不正确的构造函数被调用(从我的观点来看)。
Constructing an object using int as the generic type and passing in two ints as arguments causes the 'incorrect' constructor to be called (from my point of view).
例如。 房屋及LT; INT>房子=新房< INT>(1,2)
- 调用第二construtor。传入整数任何其他数量到构造函数将调用第一个构造函数。
E.g. Houses<int> houses = new Houses<int>(1,2)
- calls the 2nd construtor. Passing in any other number of ints into the constructor will call the 1st constructor.
有没有解决这个其他任何方式不是删除了params关键字,并迫使用户通过T的阵列使用第一个构造函数是什么时候?
Is there any way around this other than removing the params keyword and forcing users to pass an array of T when using the first constructor?
推荐答案
一个更明确的解决办法是有两个静态工厂方法。如果你把这些变成非泛型类,你也可以从类型推断受益:
A clearer solution would be to have two static factory methods. If you put these into a nongeneric class, you can also benefit from type inference:
public static class Houses
{
public static Houses<T> CreateFromElements<T>(params T[] initialElements)
{
return new Houses<T>(initialElements);
}
public Houses<T> CreateFromDefault<T>(int count, T defaultValue)
{
return new Houses<T>(count, defaultValue);
}
}
调用的例子:
Example of calling:
Houses<string> x = Houses.CreateFromDefault(10, "hi");
Houses<int> y = Houses.CreateFromElements(20, 30, 40);
那么你的泛型类型的构造并不需要PARAMS位,并且将没有混乱。
Then your generic type's constructor doesn't need the "params" bit, and there'll be no confusion.
这篇关于在泛型类型的构造函数中使用C#params关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!