C#でこのような実装はありますか?JavaScriptのスプレッド構文?
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);
ベストアンサー1
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}, ");
}
古い回答 (C# 12 以前)
スプレッドオプションはありませんが、便利な代替手段がいくつかあります。
- C#では、paramsキーワードを使用しない限り、メソッドパラメータは配列ではありません。
- param キーワードを使用するメソッド パラメータは、次のいずれかになります。
- 同じタイプを共有する
- 数値用のdoubleなどのキャスト可能な共有型を持つ
- object[]型であること(objectはすべてのもののルート型であるため)
ただし、そうは言っても、さまざまな言語機能で同様の機能を得ることができます。
あなたの例に答えると:
C#
var arr = new []{
"1",
"2"//...
};
Console.WriteLine(string.Join(", ", arr));
あなたが提供したリンクには次の例があります:
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));
パラメータ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;
}
}
}