C # having a non-static element in a static function

So I have a function:

List<string> names = new string();

private static void getName(string name)
{
    names.add(name);
}

When I try to compile, I get: "An object reference is required to notify a non-static field." What do I need to do to make this member (s) compatible with getName?

I need it to be non-stationary or transformed, because I want to put the results in other non-static functions and forms.

+5
source share
5 answers

, . , ... ? , - , . - names ?

, , :

public class Person
{
    public double MassInGrams { get; set; }
    public double HeightInMetres { get; set; }

    public static double ComputeBodyMassIndex()
    {
        // Which person are we interested in?
    }
}

Person p1 = new Person { MassInGrams = 76203, HeightInMetres = 1.8 };
Person p2 = new Person { MassInGrams = 65000, HeightInMetres = 1.7 };

double bmi = Person.ComputeBodyMassIndex();

? Person "", , . .

:

  • names .
  • , ,

, , . ...

+10

names static, :

 // If this is static, you can use it from your static method
 static List<string> names = new List<string>();

, getName , . names , .

+2

names - , , . MyClass mc = new MyClass();, mc.names. , . MyClass.getName(""); . , , , " ". , , " " , MyClass.names, getName , , no MyClass.getName("") , mc.getName(""); , .

+1

Static methods cannot access class fields. Either make the names static, or make getName () non-static. What do you mean by "Compatible". Ask yourself ... should the method be static? What is its purpose and how are you going to use it?

0
source

You cannot access this path, you need to create a class containing a member.

0
source

All Articles