c# - 如何在 C# 中将两个参数作为一个参数发送?

标签 c# parameters tuples

我的问题在于我有一个方法需要可变数量的参数。

这些参数中的每一个都是一个对象,真正的问题在于为该方法中的每个参数编写 new ClassName(p1, p2) 会变得非常冗长。

有没有办法以 {p1, p2} 的形式将 p1p2 作为单个参数发送>(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/

相关文章:

c# - 系统.Data.SqlClient.SqlException : Implicit conversion from data type sql_variant to uniqueidentifier is not allowed.

c# - 如何实现 "masterpage"级别的逻辑

c - 为什么没有参数的函数(与实际函数定义相比)可以编译?

python - 在元组列表中查找重叠元素?

python-3.x - Pandas 在多列上应用元组解包功能

python - 创建文件 python

c# - 在 NUnit 测试中处理 MessageBox

c# - 将 web.config 作为第三方 Web 服务提供商分发的正确方法

python - 参数与参数 Python

c# - 参数值类型为C#的C#中的交换方法是否无效?