Python-like list unpacking in C#?

不羁岁月 提交于 2019-12-05 02:57:40

Well, the closest would be reflection, but that is on the slow side... but look at MethodInfo.Invoke...

You can use the params keyword when defining your method and then you can directly put your list (after calling ToArray) in your method call.

public static void UseParams(params object[] list)
{
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
}

...which you can later call with the following.

object[] myObjArray = { 2, 'b', "test", "again" };
UseParams(myObjArray);

For reference: http://msdn.microsoft.com/en-us/library/w5zay9db.aspx

you cant, you can do things that are close with a bit of hand waving (either yield to a foreach, or add a foreach extension method on the collection that takes a lambda), but nothing as elegant as you get in python.

With LINQ you can do this which is pretty close to your example.

 var list = new List<int> { 3, 4 };
 var sum = list.Sum();
Func<List<float>, float> add = l => l[0] + l[1];
var list = new List<float> { 4f, 5f };
add(list); // 9

or:

Func<List<float>, float> add = l => l.Sum();
var list = new List<float> { 4f, 5f };
add(list); // 9

Is the closest you get in c# considering it's statically typed. You can look into F#'s pattern matching for exactly what you're looking for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!