Private static member variables in C#
I'm coming from an obj-c background looking at some C# code. In a partial subclass of Window, I see this at the top of the code:
public partial class MyMessage : Window
{
private static object _messageLock = new object();
private static MyMessage开发者_如何学Python _f = new MyMessage();
What are these types of member variables used for? I know you can create a static variable for a class so that it is used for the whole class (the classic example being some int count variable that will increment every time the class is instantiated in order to keep track of how many objects of that class are instantiated). In this case, I am not sure what it means.
Thanks.
private static object _messageLock = new object();
private static MyMessage _f = new MyMessage();
This looks like the class creates a Singleton of type MyMessage
and then controls access to it using a lock on the messageLock
variable - hard to verify though without the full code.
Well i can answer what the first member is used for. This is for creating a thread lock. One object which is used to mark which thread currently holds the lock and can do his business. I guess the second member is used for threading aswell, but without the rest of the code its difficult to answer.
So these two members are privat static which means only one instance of these variables no matter how many MyMessage objects are created and can only be accessed inside MyMessage instances.
These static member variables store things that are scoped to be available to every object created from that class - so one variable shared amongst 0 to many objects. These are private, so they are only available to code from within the class.
The _messageLock looks like its probably intended to be an object used in a lock() statement, somewhere in the class there is probably:
lock(_messageLock)
{
// some code
}
Or somethign using some other form of thread-safe lock. This is intended to create some form of 'one thread only' portions of the code.
Combined witht the static MyMessage - I'm guessing this is a form of singleton. There are a number of different C# singleton patterns discussed in this MSDN article
I think what you are asking is simply 'What is a static field', not 'What are the specific private static fields doing here' like everyone else seems to be answering.
A private static member variable such as the ones in your example are private member variables that can be accessed by ANY object of that class. Any instance you create of MyMessage
will be able to access those member variables.
It seems that MyMessage
is a singleton class, and it internally manages a private variable called _f
which is actually the singleton instance.
And from the name, it guess that _messageLock
is used in lock
statement, to protect critical code section, (such as in multithreaded application), as:
lock(_messageLock)
{
//critical section
}
Have a look at : lock Statement (C# Reference) at MSDN
精彩评论