【问题标题】:How to use Multiple return in c#如何在 C# 中使用多重返回
【发布时间】:2019-06-05 22:09:51
【问题描述】:

我是 C# 的新手。我想知道代码中是否有可能有很多返回。 我的代码目前无法正常工作。见下文:

public static int GeometryandControlPoints(int t, double rinn, double rout, int nx, int ny, int poly)
{
    int nel, n, m, ncp, gdof;
    nel = nx * ny;
    n = nx + poly;
    m = ny + poly;
    ncp = n * m;
    gdof = 2* ncp;
    return (nel, n, m, ncp, gdof);
}

错误位于return 行,如下图所示。

【问题讨论】:

  • 您必须声明返回类型列表。喜欢public static (int nel, int n, int m, int ncp, int gdof) Geometry...(...)
  • 你的返回类型应该是 (int , int (等等)) 在这里阅读元组docs.microsoft.com/en-us/dotnet/csharp/tuples
  • 请勿张贴代码图片。将实际代码发布到问题中。有时为了提供帮助,有人会将您的代码复制并粘贴到 Visual Studio 中,以便他们可以使用它。他们不能用图片做到这一点。这意味着这个问题不是独立的。有人应该能够在一个页面上看到问题(及其代码)和答案。
  • 解释你的目标是什么也很有帮助as well as what you are doing。可能有一种更有效或更惯用的方式来实现您的目标。

标签: c#


【解决方案1】:

按照 Filip 的建议,您可以使用 Tuple 返回多个整数:

public static Tuple<int, int, int, int, int> GeometryandControlPoints(int t, double rinn, double rout, int nx, int ny, int poly)
{
    int nel, n, m, ncp, gdof;
    nel = nx * ny;
    n = nx + poly;
    m = ny + poly;
    ncp = n * m;
    gdof = 2 * ncp;
    return new Tuple<int, int, int, int, int>(nel,n, m, ncp, gdof);
}

另一种方法是创建一个自定义 CLASS 来封装五个 int 并将其返回。

【讨论】:

  • Tuple 是一个类。它只是一个通用的,而不是为更具体的目的而编写的自定义。
猜你喜欢
  • 2016-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
  • 2021-10-14
  • 2011-08-25
相关资源
最近更新 更多