C#中的JavaScript扩展语法 [英] JavaScript spread syntax in C#

查看:89
本文介绍了C#中的JavaScript扩展语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中是否有任何实现,如 JavaScript的扩展语法

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

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

Console.WriteLine(...arr);


推荐答案

没有差价选项。还有原因。

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


  1. 属性不是C#中的数组,除非你使用params关键字

  2. 使用param关键字的属性必须:

  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. 共享相同的类型

  2. 拥有一个castable共享类型,例如double for numerics

  3. 类型为object [](因为对象是所有内容的根类型)


然而,话说回来,你可以获得具有各种语言功能的类似功能。

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

回答你的例子:

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));

参数
在C#中,类型相同

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));

在C#中,使用不同的数字类型,使用double

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));

反射
在C#中,使用不同的数字类型,使用对象和反射,这可能是你最接近你要求的。

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;
        }
    }
}

这篇关于C#中的JavaScript扩展语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆