Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a static function in a class.

whenever I try to use non static data member, I get following compile error.

An object reference is required for the nonstatic field, method, or property member

Why is it behaving like that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
193 views
Welcome To Ask or Share your Answers For Others

1 Answer

A non-static member belongs to an instance. It's meaningless without somehow resolving which instance of a class you are talking about. In a static context, you don't have an instance, that's why you can't access a non-static member without explicitly mentioning an object reference.

In fact, you can access a non-static member in a static context by specifying the object reference explicitly:

class HelloWorld {
   int i;
   public HelloWorld(int i) { this.i = i; }
   public static void Print(HelloWorld instance) {
      Console.WriteLine(instance.i);
   }
}

var test = new HelloWorld(1);
var test2 = new HelloWorld(2);
HelloWorld.Print(test);

Without explicitly referring to the instance in the Print method, how would it know it should print 1 and not 2?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...