JavaScript在C#中传播语法

0md85ypi  于 2023-11-15  发布在  Java
关注(0)|答案(6)|浏览(144)

在C#中是否有类似JavaScript's spread syntax的实现?

var arr = new []{"Hello", "World"};
Console.WriteLine(...arr);

字符串

第三方编辑

使用一种方法

public void greet(string salutation, string recipient)
{
    Console.WriteLine(salutation + " " + recipient);    
}

// instead of this
greet(arr[0], arr[1]);
// the spread syntax in javascript allows this
greet(...arr);

kxkpmulp

kxkpmulp1#

没有利差的选择,这是有原因的。
1.方法参数在C#中不是数组,除非使用params关键字
1.使用param关键字的方法参数必须是:
1.共享同一类型
1.具有可铸造的共享类型,例如用于数字的double
1.类型为object[](因为object是所有事物的根类型)
然而,话虽如此,您可以通过各种语言功能获得类似的功能。
举你的例子:

C#

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

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

字符串
你提供的链接有这个例子:

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在C#中,同类型

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

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#中,使用不同的数值类型,使用对象和反射,这可能是最接近你所要求的。

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

c86crjj0

c86crjj02#

获得类似行为(没有反射)的一个技巧是接受params SomeObject[][],并定义一个从SomeObjectSomeObject[]的隐式运算符。现在您可以传递SomeObject和单个SomeObject元素的数组的混合。

public class Item
{
    public string Text { get; }

    public Item (string text)
    {
        this.Text = text;
    }

    public static implicit operator Item[] (Item one) => new[] { one };
}

public class Print
{
    // Accept a params of arrays of items (but also single items because of implicit cast)

    public static void WriteLine(params Item[][] items)
    {
        Console.WriteLine(string.Join(", ", items.SelectMany(x => x)));
    }
}

public class Test
{
    public void Main()
    {
        var array = new[] { new Item("a1"), new Item("a2"), new Item("a3") };
        Print.WriteLine(new Item("one"), /* ... */ array, new Item("two")); 
    }
}

字符串

krugob8w

krugob8w3#

C#12引入了类似于JavaScript的spread操作符。
我们可以写

int[] row0 = [1, 2, 3];
int[] row1 = [4, 5, 6];
int[] row2 = [7, 8, 9];
int[] single = [..row0, ..row1, ..row2];

字符串

w8biq8rn

w8biq8rn4#

C#中没有直接的预构建库来处理Spread中构建的内容
为了在C#中获得该功能,您需要反射对象并通过其访问修饰符获得方法,属性或字段。
你会做这样的事情:

var tempMethods = typeof(myClass).GetMethods();
var tempFields = typeof(myClass).GetFields();
var tempProperties = typeof(myClass).GetProperties();

字符串
然后遍历并将它们扔到动态对象中:

using System;
using System.Collections.Generic;
using System.Dynamic;

namespace myApp
{
    public class myClass
    {
        public string myProp { get; set; }
        public string myField;
        public string myFunction()
        {
            return "";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var fields = typeof(myClass).GetFields();
            dynamic EO = new ExpandoObject();
            foreach (int i = 0; i < fields.Length; i++)
            {
                AddProperty(EO, "Language", "lang" + i);
                Console.Write(EO.Language);
            }
        }

        public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
        {
            // ExpandoObject supports IDictionary so we can extend it like this
            var expandoDict = expando as IDictionary<string, object>;
            if (expandoDict.ContainsKey(propertyName))
                expandoDict[propertyName] = propertyValue;
            else
                expandoDict.Add(propertyName, propertyValue);
        }
    }
}


https://www.oreilly.com/learning/building-c-objects-dynamically

rkttyhzu

rkttyhzu5#

我来这里寻找numbers[ 1 .. 4]中的C#范围运算符

int[] numbers = new[] { 0, 10, 20, 30, 40, 50 };
int start = 1, amountToTake = 3;
int[] subset = numbers[start..(start + amountToTake)];  // contains 10, 20, 30
numbers[1 .. 4] // returns 10, 20, 30

字符串
linqpad中,它看起来像这样


的数据

rta7y2nd

rta7y2nd6#

您还可以执行以下操作

var a  = new List<int>(new int[]{1,2,3}){5};
    Console.WriteLine(a.Count);

字符串
将打印4
如果你想实现列表或数组的初始化,

相关问题