What does the static modifier mean in the constructor?

I saw this code at work:

class FooPlugin : IPlugin // IPlugin is a Microsoft CRM component, it has something special about it execution
{
  static FooPlugin()
  {
     SomeObject.StaticFunction(); // The guy who wrote it said it meaningful to this question but he can't remember why.
  }
}

Any idea what a static modifier means in the constructor, and why is it required in this case?

+5
source share
6 answers

This is a static class initialization.

It will be called when using a method, field, property, or the rest of the class. In other words, this will be called the first time you use a class.

See static constructors on MSDN

Here you can also initialize static material.

, , , SomeObject.StaticFunction() , FooPlugin, , FooPlugin.

, , ( ) , inline.

. CA1810: , MSDN

+6
+3

, , :

  • - (, )
  • , ( ).
+3

. . inline , - . . , , , , , - .

class NeedsStaticConstructor
{

    private static Size s_size = new Size(100, 100); // can be done inline
    private static StringFormat s_format;            // more complex initialization needs code

    static NeedsStaticConstructor()
    {
        s_stateTextFormat = new StringFormat(StringFormatFlags.NoWrap);
        s_stateTextFormat.Alignment = StringAlignment.Near;
        s_stateTextFormat.LineAlignment = StringAlignment.Far;
    }
}
+1

A static (.. static), .

0

To add to the answers above, the static constructor (or static blocks, as in the case of Java), is executed only once when the class is first loaded into memory. The goal is to initialize static fields that would otherwise assume an appropriate default value for the data type. Sometimes I use static constructors to build an object modelwhich I want to use throughout the life cycle of the application.

0
source

All Articles