C# accesing non static member in a static function

后端 未结 5 1563
一向
一向 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:24

    names is an object that will exist in the instances of the class e.g. MyClass mc = new MyClass(); then you can access mc.names. A static field can be called without an instance of the class just with the classname, e.g. MyClass.getName(""); will work. So when you think logically, the class doesn't contain names, only 'the instances of that class' contain it. Therefore, you either make that list static too and it will be 'the same List instance' everywhere when you call MyClass.names or make the getName method non-static, and it will be only called from instances, therefore no MyClass.getName("") will be possible, but mc.getName(""); It's a matter of what you are exactly trying to do.

提交回复
热议问题