Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

JavaScript spread syntax in C#

Is there any implementation in C# like JavaScript's spread syntax?

var arr = new []{
   "1",
   "2"//...
};

Console.WriteLine(...arr);
question from:https://stackoverflow.com/questions/39886700/javascript-spread-syntax-in-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There isn't a spread option. And there are reasons.

  1. Properties aren't an array in C# unless you use the params keyword
  2. Properties that use the param keyword would have to either:
    1. Share the same type
    2. Have a castable shared type such as double for numerics
    3. Be of type object[] (as object is the root type of everything)

However, having said that, you can get similar functionality with various language features.

Answering your example:

C#

var arr = new []{
   "1",
   "2"//...
};

Console.WriteLine(string.Join(", ", arr));

The link you provide has this example:

Javascript Spread

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));

Params In C#, with same type

public int Sum(params int[] values)
{
     return values.Sum(); // Using linq here shows part of why this doesn't make sense.
}

var numbers = new int[] {1,2,3};

Console.WriteLine(Sum(numbers));

In C#, with different numeric types, using double

public int Sum(params double[] values)
{
     return values.Sum(); // Using linq here shows part of why this doesn't make sense.
}

var numbers = new double[] {1.5, 2.0, 3.0}; // Double usually doesn't have precision issues with small whole numbers

Console.WriteLine(Sum(numbers));

Reflection In C#, with different numeric types, using object and reflection, this is probably the closest to what you are asking for.

using System;
using System.Reflection;

namespace ReflectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var paramSet = new object[] { 1, 2.0, 3L };
            var mi = typeof(Program).GetMethod("Sum", BindingFlags.Public | BindingFlags.Static);
            Console.WriteLine(mi.Invoke(null, paramSet));
        }

        public static int Sum(int x, double y, long z)
        {
            return x + (int)y + (int)z;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...