我的问题在于我有一个方法需要可变数量的参数。
这些参数中的每一个都是一个对象,真正的问题在于为该方法中的每个参数编写 new ClassName(p1, p2)
会变得非常冗长。
有没有办法以 {p1, p2}
或 的形式将
?p1
和 p2
作为单个参数发送>(p1, p2)
这样我就可以编写 Insert(("John", "Doe"), ("Sherlock", "Holmes"), ... etc)
然后将它们传递到新闻中方法本身而不是编写 Insert(new Person("John", "Doe"), new Person("Sherlock", "Holmes"), ... etc)
我知道 F# 和 scala 中的元组可以这样做,但在 C# 中使用元组只会使代码更长
那么有没有办法让它不那么冗长呢?
编辑:我不想创建新数组或新列表 我想尽可能避免使用 new 关键字
Edit2:有些人要求查看我的 Insert 方法是什么样的;目前它看起来像这样:
public void Insert(params Person[] arr)
{
//inserts the person in a hash table
Action<Person> insert = (person) => _table[hasher(person.Name)].Add(person);
// calls the insert function/action for each person in the parameter array
Array.ForEach(arr, insert);
}
最佳答案
您可以创建一个支持初始化语法的集合,并将其作为您方法的参数提供。这将允许以下内容:
void Main()
{
SomeMethod(new PersonCollection{{1, 2}, {3, 4}, {5, 6}});
}
void SomeMethod(PersonCollection pc)
{
}
//...
class Person
{
public Person(int a, int b)
{
}
}
class PersonCollection:IEnumerable
{
IList<Person> personList = new List<Person>();
public void Add(int a, int b)
{
personList.Add(new Person(a,b));
}
public IEnumerator GetEnumerator()
{
return personList.GetEnumerator();
}
}
支持这种构造所需的全部是一个合适的 void Add
方法和 IEnumerable
的实现。
关于c# - 如何在 C# 中将两个参数作为一个参数发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16396521/