You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#能否像JS的...运算符那样,将元组返回值内联解构为方法参数?

Can I inline-deconstruct a tuple return value as method parameters in C#?

Yes, but C# doesn’t have a direct equivalent to JavaScript’s ... spread operator for tuples. That said, there are clean single-line solutions that don’t require modifying your existing GetTupleResult or MethodWithTwoStringParameters methods.

Here are the most practical approaches:

1. Single-line destructuring + method call (single method invocation)

You can combine the destructuring assignment and method call into one line using a semicolon. This keeps code concise and only calls GetTupleResult() once (critical if the method has side effects or is expensive to run):

(string a, string b) = GetTupleResult(); MethodWithTwoStringParameters(a, b);

2. Temporary tuple variable (cleaner single-line alternative)

If you prefer not to destructure into separate variables, store the tuple in a temporary variable and access its properties directly in the same line:

var tupleResult = GetTupleResult(); MethodWithTwoStringParameters(tupleResult.a, tupleResult.b);

Why no direct "spread" syntax?

C# doesn’t natively support inline tuple spreading into method arguments (like the MethodWithTwoStringParameters(...GetTupleResult()) syntax you asked about). Any workaround to avoid temporary variables would either:

  • Call GetTupleResult() twice (inefficient and risky if the method has side effects), like this:
    MethodWithTwoStringParameters(GetTupleResult().a, GetTupleResult().b);
    
  • Use overly complex syntax (like reflection or anonymous methods) that hurts readability and isn’t worth the tradeoff.

For most cases, the first two approaches strike the best balance of conciseness, efficiency, and readability.

内容的提问来源于stack exchange,提问作者André Reichelt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:22:40