c#中的JavaScript扩展语法

发布于 2025-02-11 16:11:04 字数 631 浏览 1 评论 0 原文

c#中是否有任何实现,例如 >?

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

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

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

3rd party edit

Using a method

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

等你爱我 2025-02-18 16:11:05

则可以执行以下

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

打印4

如果要实现列表或列表的初始化,

you can also do the following

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

will print 4

if you want to achieve initialization of lists or arrays with both an accompanying enumerable and parameters

○愚か者の日 2025-02-18 16:11:04

C#12添加了传播功能。

int[] row0 = [1, 2, 3];
int[] row1 = [4, 5, 6];
int[] row2 = [7, 8, 9];
int[] single = [..row0, ..row1, ..row2];
foreach (var element in single)
{
    Console.Write($"{element}, ");
}

https://learn.microsoft.com/en-us /dotnet/csharp/wheck-new/csharp-12

旧答案(pre c#12)

没有传播选项,而是一些有用的选择。

  1. 参数不是C#中的数组
  2. 方法
    1. 共享相同的类型
    2. 具有可铸的共享类型,例如double for Numerics
    3. 为类型对象[](作为对象是所有事物的根类型)

但是,您可以通过各种语言功能获得类似的功能。

回答您的示例:

c#

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

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

您提供的链接有此示例:

javascript vread

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#中,具有相同类型

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

C# 12 has added the spread feature.

int[] row0 = [1, 2, 3];
int[] row1 = [4, 5, 6];
int[] row2 = [7, 8, 9];
int[] single = [..row0, ..row1, ..row2];
foreach (var element in single)
{
    Console.Write(
quot;{element}, ");
}

https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12

Old answer (pre C# 12)

There isn't a spread option, but some useful alternatives.

  1. Method Parameters aren't an array in C# unless you use the params keyword
  2. Method Parameters 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;
        }
    }
}
甜味拾荒者 2025-02-18 16:11:04

C#12引入了类似于JavaScript的传播操作员。它可以使用.NET 8

我们可以写

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

C# 12 has introduced the spread operator similar to Javascript. It is available with .Net 8

We can write

int[] row0 = [1, 2, 3];
int[] row1 = [4, 5, 6];
int[] row2 = [7, 8, 9];
int[] single = [..row0, ..row1, ..row2];
苦妄 2025-02-18 16:11:04

获得与此类似的行为(无反思)的一个窍门是接受 params someObject [] [] [] ,还要从 somebobject to someobject定义隐式运算符[] 。现在,您可以将 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")); 
    }
}

One trick to get a behavior similar to this (without reflection) is to accept params SomeObject[][] and to also define an implicit operator from SomeObject to SomeObject[]. Now you can pass a mixture of arrays of SomeObject and individual SomeObject elements.

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")); 
    }
}
聊慰 2025-02-18 16:11:04

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-dynancily

there is no direct pre-built library in C# to handle what is built into Spread

In order to get that functionality in C#, you need to Reflect the object and get the methods, properties, or fields by their access modifiers.

You'd do something like:

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

then iterate through and throw them into your dynamic object:

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

孤城病女 2025-02-18 16:11:04

我来这里寻找 c#range运算符数字[1 .. 4

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'“ rel =” tag'

标记为“ linqpad”的问题“ aria-label = “ https://i.sstatic.net/wdjag.png” rel =“ nofollow noreferrer”>

I came here looking for the c# range operator as in numbers[ 1 .. 4]

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

In this looks like this

Linqpad range operator

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文