在generics类型的构造函数中使用C#params关键字

我在C#中有一个带有2个构造函数的generics类:

public Houses(params T[] InitialiseElements) {} public Houses(int Num, T DefaultValue) {} 

使用int作为generics类型构造对象并传入两个int作为参数会导致调用“不正确”的构造函数(从我的角度来看)。

例如Houses houses = new Houses(1,2) – 调用第二个construtor。 将任意其他数量的int传递到构造函数中将调用1st构造函数。

除了删除params关键字并强制用户在使用第一个构造函数时传递T数组,还有什么方法吗?

更清晰的解决方案是拥有两种静态工厂方法。 如果将这些放入非generics类中,您还可以从类型推断中受益:

 public static class Houses { public static Houses CreateFromElements(params T[] initialElements) { return new Houses(initialElements); } public Houses CreateFromDefault(int count, T defaultValue) { return new Houses(count, defaultValue); } } 

调用示例:

 Houses x = Houses.CreateFromDefault(10, "hi"); Houses y = Houses.CreateFromElements(20, 30, 40); 

然后你的generics类型的构造函数不需要“params”位,并且不会有任何混淆。

也许代替Params你可以传入IEnumerable

 public Houses(IEnumerable InitialiseElements){} 

第二个构造函数是一个更精确的匹配,这是用于评估哪个构造函数是正确的标准。

考虑到以下因为原来没有关于class级等的太多信息。

编译器将决定新的House(1,2)与第二个构造函数完全匹配并使用它,注意我用最多的投票得到了答案但它没有用。

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericTest { public class House { public House(params T[] values) { System.Console.WriteLine("Params T[]"); } public House(int num, T defaultVal) { System.Console.WriteLine("int, T"); } public static House CreateFromDefault(int count, T defaultVal) { return new House(count, defaultVal); } } class Program { static void Main(string[] args) { House test = new House(1, 2); // prints int, t House test1 = new House(new int[] {1, 2}); // prints parms House test2 = new House(1, "string"); // print int, t House test3 = new House("string", "string"); // print parms House test4 = House.CreateFromDefault(1, 2); // print int, t } } }