直接在函数参数内创建包含值的列表

时间:2015-02-11 05:53:06

标签: c#

而不是:

void MyFunction(List<float> list)
{
    // do something
}

List<float> myList = new List<float>();
myList.Add(3.0);
myList.Add(4.0);
MyFunction(myList);

有没有办法做这样的事情?

MyFunction(new List<float>{3.0,4.0}());

意思是我将所有初始化直接保留在函数参数本身内。

3 个答案:

答案 0 :(得分:1)

你真的很亲密。删除最后一对括号(并将你的双打投射到浮点数):

MyFunction(new List<float> { 3.0f, 4.0f });

答案 1 :(得分:1)

添加有关最酷params关键字的信息。它允许您执行以下操作:

void MyFunction(params float[] list)
{
    // do something
}

MyFunction(new float[] { 3.0f, 4.0f }); // valid call
MyFunction(3.0f, 4.0f); // also valid
MyFunction(32f); // also valid
MyFunction(); // also valid, beware! list will be an empty array
MyFunction(null); // also valid, beware! list will be null

请注意,执行此操作:new float[] { 3.0f, 4.0f }是所谓的集合初始值设定项。无论是否将其作为参数发送,都可以使用它。其他的是使用关键字params的好处,这实际上只是使它更短,更容易使用。

答案 2 :(得分:1)

您可以使用collection initializerparams array

您的示例无法编译,因为禁止隐式强制转换,精度损失从double到float。

您需要一个精度低于目标类型,精确类型数字文字或显式强制转换的数字文字。

以下示例显示了方法参数中的List和params数组初始化:

    [TestMethod]
    public void TestMethod1()
    {
        // Original code with correct constant type.
        MyFunction(new List<float> { 3.0f, 4.0f });

        // Using an overload with a params array argument.
        MyFunction(3.0f, 4.0f);

        // Various float constant flavours.
        MyFunction(3f, 3.0f, .0f, 3e-10f, (float)3);

        // Implicit cast to float from anything with lesser precision or an explicit cast to float.
        MyFunction((byte)1, (short)1, (int)1, 1, (long)1, 1L, (float)1);
    }

    void MyFunction(List<float> list)
    {
        throw new NotImplementedException();
    }

    void MyFunction(params float[] args)
    {
        throw new NotImplementedException();
    }
相关问题