【问题标题】:Pass an argument in static void function C#在静态 void 函数 C# 中传递参数
【发布时间】:2014-02-09 01:12:21
【问题描述】:

我正在尝试编写一个 C# 函数来确定数组中的最大值并通过引用传递它。

这是我第一次使用 C# 编程,但我似乎无法在 main 中正确分配它,这让我很烦恼。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Program
    {
        static void Maxim(int n, ref int maxim, params int[] v) {
            int i,  max=v[0];

            for (i = 0; i < n; i++) {
                if (v[i] >  max)  max = v[i];
            }
        }

        static void Main()
        {
            int[] vector = new int[10];
            int n, i;
            int maximul;

            Console.WriteLine("Introduceti numarul de elemente: ");
            n = Int32.Parse(Console.ReadLine());

            Console.WriteLine("Valoarea introdusa: {0}", n);
            for (i = 0; i < n; i++) {
                vector[i] = Int32.Parse(Console.ReadLine());
            }

            Console.WriteLine("Elementele introduse sunt: ");
            for (i = 0; i < n; i++) {
                Console.WriteLine("Elementul {0}:  {1}", i + 1, vector[i]);
            }

            Maxim(n, ref maximul, vector);

            Console.WriteLine("Maximul din vector: {0}",  maximul);
            Console.ReadLine();
        }
    }
}

它返回以下错误:Use of unassigned local variable

【问题讨论】:

  • 尝试设置 maximul=0;在声明中。
  • 您永远不会在 Maxim 函数中分配 maxim
  • 查看此问题的最佳答案以获取有关 outref 的解释:stackoverflow.com/questions/135234/…

标签: c# function void


【解决方案1】:

在定义变量时初始化变量:

int n = 0, i = 0;
int maximul = 0;

可能的原因是您将 maximul 作为 ref 参数传递但您没有对其进行初始化。

来自documentation

传递给 ref 参数的参数必须在传递之前初始化。这与 out 参数不同,后者的参数在传递之前不必显式初始化。

【讨论】:

  • 是的,现在我明白了!非常感谢!
  • 您不需要在代码中使用 ref。只要传递价值就可以了。并且根本没有使用 maximul。
【解决方案2】:

Maxim 是一个冗余变量。你永远不会在你的函数中使用它。

【讨论】:

    【解决方案3】:

    问题是最大值存储在本地max 中,但调用者希望将其写入ref 参数maxim。如果您删除本地的max 并改用maxim,这将解决问题。

    编写此函数的更惯用的方法是根本不使用ref 参数。而是直接返回值

    static intMaxim(int n, params int[] v) {
      int i,  max=v[0];
      for (i = 0; i < n; i++) {
        if (v[i] >  max)  max = v[i];
      }
      return max;
    }
    

    注意n 参数在这里也不是真正需要的。数组v的长度可以通过表达式v.Length访问

    【讨论】:

      猜你喜欢
      • 2019-02-21
      • 2021-11-19
      • 2010-12-19
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 2019-04-25
      相关资源
      最近更新 更多