【发布时间】: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 -
哦,有道理。谢谢。