سؤال

Why can't I change the backcolor of my form this way?

MainForm.BackColor = System.Drawing.Color.Black;

This is what I get in the console:

An object reference is required for the non-static field, method, or property 'System.Windows.Forms.Control.BackColor.get' (CS0120) 
هل كانت مفيدة؟

المحلول

Static Classes are classes that cannot be instantiated. Static classes have static methods or static properties (or both). When you use a line like this:

MainForm.BackColor = System.Drawing.Color.Black; // <class name>.<property>

What the C# compiler does first is look for a local class variable called MainForm. Since there was none, it then looked outside your local scope and found your Windows.Form class called MainForm.

It then looked to see if the class MainForm has a static property called BackColor. The compiler then said "Oh look, there is a property called BackColor, but its not static", which is when the compiler complained and threw you the error you experienced.

By changing it to this.BackColor, the compiler knew you wanted to set the background color OF THIS INSTANCE of MainForm, which was this or, by default, form1:

this.BackColor = System.Drawing.Color.Black; // <this instance>.<property>

And as a side note, the keyword this is not required. Omitting it assumes "this object". You can do this just as well:

BackColor = System.Drawing.Color.Black; // <this instance>.<property>

Hope this makes more sense!

نصائح أخرى

You're using MainForm as if it were a static class. Either make your form static or create an instance of it.

MainForm form = new MainForm();

Then use

form.BackColor = Color.Black;

Adding to the comment to your question, stick

 this.BackColor = Color.Black;

inside of a method of your form, and just call that method. Like so.

void changeBackColor(Color color)
{
    this.BackColor = color;
}

That will let you pass a color to the method and changes the BackColor accordingly.

Hope this helps. I'd recommend reading a book about C#. Objects can't be used before being initialized. It's a pretty elementary concept.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top