jmv*_*dad 27 javascript c# spread-syntax
在C#中是否有像JavaScript的扩展语法一样的实现?
var arr = new []{
"1",
"2"//...
};
Console.WriteLine(...arr);
Run Code Online (Sandbox Code Playgroud)
Rhy*_*ous 13
没有传播选项.而且有原因.
但是,话虽如此,您可以获得具有各种语言功能的类似功能.
回答你的例子:
C#
var arr = new []{
"1",
"2"//...
};
Console.WriteLine(string.Join(", ", arr));
Run Code Online (Sandbox Code Playgroud)
您提供的链接有以下示例:
Javascript传播
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));
Run Code Online (Sandbox Code Playgroud)
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));
Run Code Online (Sandbox Code Playgroud)
在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));
Run Code Online (Sandbox Code Playgroud)
反射 在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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
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];
Run Code Online (Sandbox Code Playgroud)
获得与此类似的行为(无需反射)的一个技巧是接受params SomeObject[][]并定义一个隐式运算符 from SomeObjectto 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"));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13265 次 |
| 最近记录: |