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

如何在C#对象初始化器语法中直接使用命名元组的值?

直接用命名元组初始化对象属性的写法需求

我希望能直接通过命名元组的返回值来初始化对象的属性,期望采用如下写法:

public Person DoIt() {
  return new Person {
    (First, Last) = GetFirstAndLast(id)
  };
}

public (string first, string last) GetFirstAndLast(int id) {
  return ("First name", "Last name");
}

我清楚可以通过以下方式实现相同效果,但不想引入额外的中间变量:

public Person DoIt()
{
    var (first, last) = GetFirstAndLast(0);
    return new Person
    {
        First = first,
        Last = last
    };
}

内容的提问来源于stack exchange,提问作者comecme

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:30:59