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

C#函数如何同时返回字符串列表和泛型类型集合

C# 方法返回多个值的实现方案

C# 支持多种实现方法返回多值的方案,以下是对应你需求的常用实现方式:

方案1:值元组(C# 7.0+ 优先推荐)

无需额外定义类,语法简洁,适合临时返回多值的场景:

// 方法定义,元组包含两个返回值
public (List<string> InfoList, SomeType OtherData) GetInfo()
{
    var result = new List<string>();
    var someTypeInstance = new SomeType
    {
        someOthertype = new List<SomeOthertype>()
    };
    // 直接返回两个值的元组
    return (InfoList: result, OtherData: someTypeInstance);
}

// 你的自定义类型
public class SomeType
{
    public List<SomeOthertype> someOthertype { get; set; }
}

// 调用示例
public void Test()
{
    var res = GetInfo();
    var info = res.InfoList;
    var otherData = res.OtherData;
    // 也支持解构写法
    var (infoList, otherData1) = GetInfo();
}

方案2:自定义返回包装类

适合返回结构需要多处复用、需要添加额外属性或方法的场景:

// 定义返回值包装类
public class GetInfoResult
{
    public List<string> InfoList { get; set; }
    public SomeType OtherData { get; set; }
}

// 方法实现
public GetInfoResult GetInfo()
{
    var result = new List<string>();
    var someTypeInstance = new SomeType
    {
        someOthertype = new List<SomeOthertype>()
    };
    return new GetInfoResult
    {
        InfoList = result,
        OtherData = someTypeInstance
    };
}

// 你的自定义类型
public class SomeType
{
    public List<SomeOthertype> someOthertype { get; set; }
}

方案3:out 参数(兼容老版本C#)

适合需要兼容C# 7.0以下版本的场景,目前不优先推荐:

// 方法定义,第二个值通过out参数返回
public List<string> GetInfo(out SomeType otherData)
{
    var result = new List<string>();
    // 给out参数赋值
    otherData = new SomeType
    {
        someOthertype = new List<SomeOthertype>()
    };
    return result;
}

// 你的自定义类型
public class SomeType
{
    public List<SomeOthertype> someOthertype { get; set; }
}

// 调用示例
public void Test()
{
    var otherData = new SomeType();
    var infoList = GetInfo(out otherData);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:15:10