【问题标题】:How to return multiple values in a method in C#.... Is it possible? [duplicate]如何在 C# 中的方法中返回多个值....有可能吗? [复制]
【发布时间】:2018-12-24 17:45:01
【问题描述】:

我一直在 Visual Studio 中使用 C# 处理我的软件。但是我想在我的方法中返回多个值,如何在 C# 中的方法中返回多个值....有可能吗??

【问题讨论】:

  • 你需要使用元组请看上面的回答。
  • 为了代码的清晰,最好创建类来保存数据并返回它。否则,您可以将数组用于相同类型或元组的值,如果您不关心类型安全,则可以使用对象数组或匿名对象。
  • @CrudaLilium AFAIK 匿名类型被键入
  • @bradbury9 你不能定义匿名返回类型,为了能够编译你必须将返回类型指定为对象或动态,因此失去了类型安全性。
  • @CrudaLilium 虽然在本地使用它们是类型安全的,但在这种特定情况下你是对的

标签: c# visual-studio methods return c#-3.0


【解决方案1】:

您可以使用 .NET 4.0+ 的元组:

例如:

public Tuple<int, int> GetMultipleValue()
{
    return Tuple.Create(1,2);
}

现在容易多了

例如:

public (int, int) GetMultipleValue()
{
    return (1,2);
}

【讨论】:

    【解决方案2】:

    您想返回单一类型的值吗?在这种情况下,您可以返回一个值数组。如果您想返回不同类型的值,您可以创建具有指定参数的对象、结构或元组,然后将这些值分配给这些参数。创建对象后,您可以从方法中返回它。

    以对象为例:

    public class DataContainer
    {
        public string stringType { get; set; }
        public int intType { get; set; }
        public bool boolType {get; set}
    
        public DataContainer(string string_type, int int__type, bool bool_type)
        {
           stringType = string_type;
           intType = int__type;
           boolType = bool_type;
        }
    }
    

    结构示例:

    public struct DataContainer
    {  
        public stringstringType;  
        public int intType;  
        public bool boolType;  
    }  
    

    元组示例:

    var DataContainer= new Tuple<string, int, bool>(stringValue, intValue, boolValue);
    

    【讨论】:

    • 尽量避免回答重复的问题,Natalia's comment 中链接的问题确实提供了这个例子,并且已经提供了更多。
    【解决方案3】:

    您可以创建一个内部包含多个变量的结构。

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct

    【讨论】:

      【解决方案4】:

      您的选项返回structclass、(命名?)tuple,或者您也可以使用out parameters

      【讨论】:

        猜你喜欢
        • 2011-04-07
        • 1970-01-01
        • 2019-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-18
        • 2014-04-04
        • 2013-02-23
        相关资源
        最近更新 更多