【问题标题】:Resolving "An object reference is required for the non-static field" error [duplicate]解决“非静态字段需要对象引用”错误[重复]
【发布时间】:2016-05-17 21:46:42
【问题描述】:

我在 C# Visual Studio 中遇到以下我无法解决的错误:

“非静态字段需要对象引用”

我不知道这意味着什么,也不知道如何解决它。当然,我在网上查了一下,但没有找到与下面我的简单代码相关的任何内容。我要做的就是成功地从 Main() 调用以下内容:

int 结果 = MaxPair(nums);

非常感谢。


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

namespace MaxPairSpace
{
    class Program
    {

        static int Main(string[] args)
        {

            int n = Int32.Parse( Console.ReadLine() );

            string input = Console.ReadLine();
            string[] split = input.Split(' ');
            int length = split.Length;
            int[] nums = new int[length];
            for (int x = 0; x < length; x++)
            {
                nums[x] = Int32.Parse(split[x]);
            }

            int result = MaxPair(nums);

            Console.WriteLine("{0}\n", result);
            return 0;
        }

        public int MaxPair(int[] numbers)
        {
            int result = 0;
            int n = numbers.Length;
            for (int i = 0; i < n; ++i)
            {
                for (int j = i; j < n; ++j)
                {
                    if (numbers[i] * numbers[j] > result)
                    {
                        result = numbers[i] * numbers[j];
                    }
                }
            }
            return result;
        } 
    }
}

【问题讨论】:

  • MaxPair设为静态。
  • 对此进行谷歌搜索,它还将解释您是否知道Instance and Static 之间的区别,如果您想从内部访问公共方法,您应该多阅读 C# 基础知识一个静态主然后你应该做 var prg = new Program() 例如然后你可以调用 prg.MaxPair() method 否则更改 Method Signature to static
  • 哦,有道理。谢谢。

标签: c# object reference


【解决方案1】:

您不能直接在静态方法中访问非静态方法/变量/属性。要访问这些项目,您需要创建相应类的实例,并通过该实例访问它们,因为您可以访问静态方法中的其他静态方法/变量/属性。如果这些项目属于不同的类,那么您可以通过它们的类名访问它们。即ClassName.Method()。所以这里更好的选择是更改方法签名,如下所示:

public static int MaxPair(int[] numbers)
{
   // Code here 
}

【讨论】:

  • 非常感谢。我完全理解。是的,我是这里的新手,我的大部分项目都是在类中实现和调用的功能。这一次,它应该是一个从 main() 调用的简单方法。但我明白了。非常感谢,现在已经解决了。
猜你喜欢
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多