C# 上的对象引用未设置错误

Object Reference Not Set Error on C#

我刚接触 Visual C#,只想创建一个基于 CLI 的小型应用程序。使用下面的书面代码,我收到此错误:"Object reference not set to an instance of an object."。 显然,由于我是菜鸟,所以我不知道如何解决这个问题。

这是我在 Program.cs 中的代码:

class Program
{
    static void Main(string[] args)
    {
        GetAverage(args);
    }

    static void GetAverage(string[] s)
    {
        var ave = new Average();

        ave.arg = s;
        ave.FindAverage();
        ave.DisplayResult();
    }
}

这是我在 Average.cs:

中的代码
public class Average
{
    public Average()
    {
        Console.Write("\n" + "Given numbers: ");

        foreach (string s in this.arg)
        {
            Console.Write(this.arg + " ");

            num += Double.Parse(s);
        }
    }

    public double num = 0;
    public string[] arg;
    public double result;

    public void FindAverage()
    {
        this.result = this.num / this.arg.Length;
    }

    public void DisplayResult()
    {
        Console.WriteLine("\n" + "Average: " + this.result);
    }
}

我想做的是从程序 class 的 Main 方法访问参数,以便我可以从平均值 class 中使用它。

请帮我解决这个问题。谢谢!

字段public string[] arg;在你的构造函数中使用,但它是在构造函数有运行之后设置的。尝试这样的事情:

public Average(string[] arg)
{
    this.arg = arg

    // ..
    // existing code
}