C# accesing non static member in a static function

后端 未结 5 1582
一向
一向 2020-12-11 18:59

So I have a function:

List names = new string();

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

When I at

5条回答
  •  余生分开走
    2020-12-11 19:13

    You need to tell the system which list of names you're interested in. It's part of the state of an object, an instance of the class... but which one? Maybe you've created several instances of the class - maybe you've created no instances of the class. The static method has no visibility of that - so which instance do you want it to fetch the names variable value from?

    To put it in another example, suppose we had a class like this:

    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();
    

    What would you expect the result to be? You've asked the Person class to compute "the BMI" but without telling it whose BMI to compute. You need to give it that information.

    Some options for your situation:

    • Change names to be static instead
    • Change the method to be an instance method
    • Pass in an instance of the class
    • Create an instance of the class, possibly returning it
    • Fetch an instance of the class some other way

    By the way, that's a very strange method name for something which adds a name. It's also somewhat unconventional...

提交回复
热议问题