الدالة الإنشائية الثابتة (إرشادات برمجة C#)

يتم إستخدام الدالة الإنشائية الثابتة لتهيئة أي بيانات ثابت، أو القيام بإجراء معين يحتاج لتنفيذ مرة واحدة فقط. ويسمى تلقائياً قبل أن يتم إنشاءالمثيل الأول أو أي أعضاء ثابتة يتم الرجوع إليها.

class SimpleClass
{
    // Static variable that must be initialized at run time.
    static readonly long baseline;

    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}

الدوال الإنشائية الثابتة لها الخصائص التالية:

  • الدالة الإنشائية الثابتة لا تأخذ معدلات الوصول و ليس لها معلمات.

  • يتم إستدعاء الدالة الإنشائية الثابتة لتهيئة الفئة قبل إنشاء مثيل الأول أو أي أعضاء ثابتة يتم الرجوع إليها.

  • لا يمكن استدعاء الدالة الإنشائية الثابتة مباشرة.

  • لا يملك المستخدم التحكم على عند تنفيذ الدالة الإنشائية الثابتة في البرنامج.

  • الإستخدام النموذجي للدوال الإنشائية االثابتة هي عندما تستخدم الفئة ملف لبسجل ويتم استخدام الدالة الإنشائية لكتابة الإدخالات إلى هذا الملف.

  • الدوال الإنشائية الثابتة عند إنشاء فئات المجمع للتعليمات البرمجية غير المدارة، عندما يمكن استدعاء المنشئ في LoadLibrary.

  • إذا كانت الدالة الإنشائية الثابتة تطرح استثناء, فإن وقت التشغيل لن يستدعي فوقه مرة ثانية ثم سيبقى النوع غير مهيأ لبقائه في مجال تطبيق تشغيل البرنامج.

مثال

في هذا المثال، الفئة Bus تحتوي على دالة إنشائية ثابتة. عند أول مثيل Bus يتم إنشاءه (bus1) ، و يتم استدعاء الدالة الإنشائية الثابتة لتهيّيئ الفئة. يقوم إخراج النموذج بالتحقق من أن الدالة الإنشائية الثابتة و يعمل مرة واحدة فقط, بالرغم من مثيلين من Bus يتم إنشاءه وإعادة تشغيله قبل تشغيل مُنشئ مثيل.

    public class Bus
    {
        // Static variable used by all Bus instances.
        // Represents the time the first bus of the day starts its route.
        protected static readonly DateTime globalStartTime;

        // Property for the number of each bus.
        protected int RouteNumber { get; set; }

        // Static constructor to initialize the static variable.
        // It is invoked before the first instance constructor is run.
        static Bus()
        {
            globalStartTime = DateTime.Now;

            // The following statement produces the first line of output, 
            // and the line occurs only once.
            Console.WriteLine("Static constructor sets global start time to {0}",
                globalStartTime.ToLongTimeString());
        }

        // Instance constructor.
        public Bus(int routeNum)
        {
            RouteNumber = routeNum;
            Console.WriteLine("Bus #{0} is created.", RouteNumber);
        }

        // Instance method.
        public void Drive()
        {
            TimeSpan elapsedTime = DateTime.Now - globalStartTime;

            // For demonstration purposes we treat milliseconds as minutes to simulate
            // actual bus times. Do not do this in your actual bus schedule program!
            Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",
                                    this.RouteNumber,
                                    elapsedTime.TotalMilliseconds,
                                    globalStartTime.ToShortTimeString());
        }
    }

    class TestBus
    {
        static void Main()
        {
            // The creation of this instance activates the static constructor.
            Bus bus1 = new Bus(71);

            // Create a second bus.
            Bus bus2 = new Bus(72);

            // Send bus1 on its way.
            bus1.Drive();

            // Wait for bus2 to warm up.
            System.Threading.Thread.Sleep(25);

            // Send bus2 on its way.
            bus2.Drive();

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
    /* Sample output:
        Static constructor sets global start time to 3:57:08 PM.
        Bus #71 is created.
        Bus #72 is created.
        71 is starting its route 6.00 minutes after global start time 3:57 PM.
        72 is starting its route 31.00 minutes after global start time 3:57 PM.      
   */

راجع أيضًا:

المرجع

الفئات والبنيات (دليل البرمجة لـ #C)

دالات الإنشاء (دليل البرنامج لـ #C)

المتلفات ( ارشادات البرمجة #C )

المبادئ

دليل البرمجة لـ #C