开发者

C# object reference question

I am creating a really basic program, that has a method to fill an array but I am getting an error I don't understand. I am a Java programmer trying to acclimate to C# and .NET. Any help would be g开发者_如何转开发reat.

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

namespace TestThreads
{
    class Program
    {
        static void Main(string[] args)
        {
             int[]  empty = new int[50001];
             int[] filled = new int[50001];

            filled = compute(empty); //error occurs here

            Console.ReadLine();
        }

        public int[] compute(int[] inArray)
        {
            for (int i = 0; i < inArray.Length; i++)
            {
                inArray[i] = i << 2;
            }

            return inArray;
        }
    }
}

Error Message:

Error 1 An object reference is required for the non-static field, method, or property 'TestThreads.Program.compute(int[])' C:\Users\hunter.mcmillen\Desktop\TestProcessSplitting\TestProcessSplitting\Program.cs 17 22 TestThreads

Thanks, Hunter


The compute method should be static.

public static int[] compute(int[] inArray)


You're trying to call compute which is an instance method from Main which is a static method. To fix this make compute static as well`

public static int[] compute(int[] inArray) 


Main is a static method - it is not specific to any single object - indeed, no instance of Program is created to call Main. compute is an instance method, and needs to be invoked on a single object.

Two options:

  1. make compute static, which makes sense since it uses no state (fields):

    public static int[] compute(int[] inArray) {...}
    
  2. create an instance in Main:

    var obj = new Program();
    filled = obj.compute(empty); 
    

The first is more appealing here. I've included the second purely for completeness.


Change public int[] compute(int[] inArray){...}

to

public static int[] compute(int[] inArray){..}

or change your call from

filled = compute(empty); 

to

filled = new Program().compute(empty); 

The compute() method that you have is an instance (non-static) method and requires an instance to be invoked.


Add static to the compute method declaration.

public static int[] compute(int[] inArray)


You're method is not static, but is being referenced from a static method. Change it to static. Solved.

public static int[] compute(int[] inArray) { ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜