web-dev-qa-db-fra.com

Erreur C #: "Une référence d'objet est requise pour le champ, la méthode ou la propriété non statique"

J'ai deux classes, une pour définir les paramètres de l'algorithme et une autre pour implémenter l'algorithme:

Classe 1 (paramètres de l'algorithme):

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

namespace VM_Placement
{
    public static class AlgorithmParameters
    {
        public static int pop_size = 100;
        public static double crossover_rate = 0.7;
        public static double mutation_rate = 0.001;

        public static int chromo_length = 300;
        public static int gene_length = 4;
        public static int max_allowable_generations = 400;

        static Random Rand = new Random();
        public static double random_num = Rand.NextDouble();
    }
}

Classe 2 (algorithme d'implémentation):

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

namespace VM_Placement
{
    public class Program
    {
        public struct chromo_typ
        {
            public string   bits;
            public float    fitness;

            //public chromo_typ(){
            // bits = "";
            // fitness = 0.0f;
            //}
            chromo_typ(string bts, float ftns)
            {
                bits = bts;
                fitness = ftns;
            }
        };

        public static int GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng =
              new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }

        public string GetRandomBits()
        {
            string bits="";

            for (int i = 0; i < VM_Placement.AlgorithmParameters.chromo_length; i++)
            {
                if (VM_Placement.AlgorithmParameters.random_num > 0.5f)
                    bits += "1";
                else
                    bits += "0";
            }
            return bits;
        }

        public static void Main(string[] args)
        {
            Random rnd = new Random(GetRandomSeed());

            while (true)
            {
                chromo_typ[] Population = new chromo_typ[VM_Placement.AlgorithmParameters.pop_size];
                double Target;

                Console.WriteLine("\n Input a target number");
                Target = Convert.ToDouble(Console.ReadLine());

                for (int i = 0; i < VM_Placement.AlgorithmParameters.pop_size; i++)
                {
                    Population[i].bits = GetRandomBits();
                    Population[i].fitness = 0.0f;
                }
            }
        }
    }
}

Je reçois une erreur sur Population[i].bits = GetRandomBits(); dans Main().

L'erreur est:

Une référence d'objet est requise pour le champ, la méthode ou la propriété non statique 'VM_Placement.Program.GetRandomBits ()'.

Est-ce que je manque quelque chose?

39
user1277070

La méthode Main est statique. Vous ne pouvez pas invoquer une méthode non statique à partir d'une méthode statique.

GetRandomBits()

n'est pas une méthode statique. Soit vous devez créer une instance de Program

Program p = new Program();
p.GetRandomBits();

ou faire

GetRandomBits() statique.

87
Sandeep

On dirait que tu veux:

public static string GetRandomBits()

Sans static, vous auriez besoin d'un objet avant de pouvoir appeler la méthode GetRandomBits(). Cependant, étant donné que l'implémentation de GetRandomBits() ne dépend pas de l'état d'un objet Program, il est préférable de le déclarer static.

10
Greg Hewgill

La méthode Main est statique dans la classe Program. Vous ne pouvez pas appeler une méthode d'instance depuis une méthode statique, c'est pourquoi vous obtenez l'erreur.

Pour résoudre ce problème, il vous suffit de rendre votre méthode GetRandomBits() statique également.

2
Karl Nicoll