المنشئات (F#)

يصف هذا pic إلى كيف إلى تعريف واستخدام construcإلىrs إلى إنشاء وتهيئة الكائنات الفئة وبنية.

الإنشاء من كائنات فئة

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

يحتوي الدالة الإنشائية الأساسي على letو doالروابط التي تظهر في بداية تعريف فئة. letالتصريح ربط حقول الخاصة والأساليب الخاصة فئة؛ doالربط بتنفيذ تعليمات برمجية. ل المزيد من المعلومات حول letروابط في المنشئات الفئة، راجع ترك للربط في فئات (F#). لمزيد من المعلومات حول doراجع الارتباطات في المنشئات، قم بإجراء الربط في فئات (F#).

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

توضح التعليمة البرمجية التالية فئة الذي يحتوي على الدالة الإنشائية وطرق مختلفة لإنشاء الكائنات.

// This class has a primary constructor that takes three arguments
// and an additional constructor that calls the primary constructor.
type MyClass(x0, y0, z0) =
    let mutable x = x0
    let mutable y = y0
    let mutable z = z0
    do
        printfn "Initialized object that has coordinates (%d, %d, %d)" x y z
    member this.X with get() = x and set(value) = x <- value
    member this.Y with get() = y and set(value) = y <- value
    member this.Z with get() = z and set(value) = z <- value
    new() = MyClass(0, 0, 0)

// Create by using the new keyword.
let myObject1 = new MyClass(1, 2, 3)
// Create without using the new keyword.
let myObject2 = MyClass(4, 5, 6)
// Create by using named arguments.
let myObject3 = MyClass(x0 = 7, y0 = 8, z0 = 9)
// Create by using the additional constructor.
let myObject4 = MyClass()

الإخراج هو كما يلي.

Initialized object that has coordinates (1, 2, 3)
Initialized object that has coordinates (4, 5, 6)
Initialized object that has coordinates (7, 8, 9)
Initialized object that has coordinates (0, 0, 0)

إنشاء بنيات

Structures follow الجميع the rules of فئات. Therefore, you can have a primary الدالة الإنشائية, و you can provide إضافى constructors بواسطة using new. However, there هو واحد important difference between structures و فئات: structures can have a الافتراضي الدالة الإنشائية (that هو, واحد مع لا الوسيطات) even if لا primary الدالة الإنشائية هو defined. The الافتراضي الدالة الإنشائية initializes الجميع the حقول إلى the القيمة افتراضية for that نوع, usually zero أو its equivalent. أي constructors that you define for structures must have على الأقل واحد وسيطة so that they do not conflict مع the الافتراضي الدالة الإنشائية.

Also, structures often have حقول that are تاريخ الإنشاء بواسطة using the val كلمة أساسية; فئات can also have these حقول. Structures و فئات that have حقول defined بواسطة using the val كلمة أساسية can also be initialized في إضافى constructors بواسطة using سجل expressions, كـ shown في the following تعليمات برمجية.

type MyStruct =
    struct
       val X : int
       val Y : int
       val Z : int
       new(x, y, z) = { X = x; Y = y; Z = z }
    end

let myStructure1 = new MyStruct(1, 2, 3) 

لمزيد من المعلومات، راجع حقول واضحة: قيمة كلمة أساسية (F#).

Executing Side تأثيرات في Constructors

A primary الدالة الإنشائية في a فئة can ينفذ تعليمات برمجية في a do ربط. However, what if you have إلى ينفذ تعليمات برمجية في an إضافى الدالة الإنشائية, without a do ربط? إلى do this, you استخدم the then كلمة أساسية.

 // Executing side effects in the primary constructor and
 // additional constructors.
 type Person(nameIn : string, idIn : int) =
     let mutable name = nameIn
     let mutable id = idIn
     do printfn "Created a person object."
     member this.Name with get() = name and set(v) = name <- v
     member this.ID with get() = id and set(v) = id <- v
     new() = 
         Person("Invalid Name", -1)
         then
             printfn "Created an invalid person object."

 let person1 = new Person("Humberto Acevedo", 123458734)
 let person2 = new Person()

The side تأثيرات of the primary الدالة الإنشائية still ينفذ. Therefore, the إخراج هو كـ follows.

Created a person object.
Created a person object.
Created an invalid person object.

Self Identifiers في Constructors

في غير ذلك الأعضاء, you provide a اسم for the الحالي كائن في the تعريف of each عضو. You can also put the self معرّف تشغيل the أول خط of the فئة تعريف بواسطة using the as كلمة أساسية immediately following the الدالة الإنشائية معلمات. The following مثال illustrates this بناء الجملة.

type MyClass1(x) as this =
    // This use of the self identifier produces a warning - avoid.
    let x1 = this.X
    // This use of the self identifier is acceptable.
    do printfn "Initializing object with X =%d" this.X
    member this.X = x

في المنشئات إضافى، يمكنك أيضا تعريف الذاتي معرّف بواسطة وضع asجملة الصحيح بعد معلمات الدالة الإنشائية. The following مثال illustrates this بناء الجملة.

type MyClass2(x : int) =
    member this.X = x
    new() as this = MyClass2(0) then printfn "Initializing with X = %d" this.X

يمكن أن تحدث مشاكل عند محاولة استخدام كائن قبله هو المعرفة بشكل كامل. ولذلك، يستخدم معرّف ذاتيا يمكن أن يؤدي المترجم للإرسال بتحذير وإدراج عمليات فحص إضافى لضمان لم يتم الوصول إلى الأعضاء كائن من قبل الكائن هو تهيئة. ينبغي عليك فقط استخدم معرّف ذاتيا في doروابط الدالة الإنشائية الأساسي، أو بعد thenكلمة أساسية في المنشئات إضافى.

لا يحتوي اسم المعرّف ذاتيا إلى يكون this. يمكن أن يكون أي معرّف صالح.

تعيين قيم إلى خصائص في تهيئة

يمكنك تعيين قيم لخصائص كائن الفئة في التهيئة تعليمات برمجية بإلحاق قائمة تعيينات نموذج property = valueإلى قائمة وسيطة الدالة الإنشائية. يظهر هذا في التعليمات البرمجية التالية.

 type Account() =
     let mutable balance = 0.0
     let mutable number = 0
     let mutable firstName = ""
     let mutable lastName = ""
     member this.AccountNumber
        with get() = number
        and set(value) = number <- value
     member this.FirstName
        with get() = firstName
        and set(value) = firstName <- value
     member this.LastName
        with get() = lastName
        and set(value) = lastName <- value
     member this.Balance
        with get() = balance
        and set(value) = balance <- value
     member this.Deposit(amount: float) = this.Balance <- this.Balance + amount
     member this.Withdraw(amount: float) = this.Balance <- this.Balance - amount
    
   
 let account1 = new Account(AccountNumber=8782108, 
                            FirstName="Darren", LastName="Parker",
                            Balance=1543.33)

الإصدار التالي من التعليمة البرمجية السابقة يوضح تركيبة الوسائط العادية، وسيطات اختيارية، و إعدادات الخصائص في استدعاء المنشئ واحد.

 type Account(account_number : int, ?first: string, ?last: string, ?bal : float) =
     let mutable balance = defaultArg bal 0.0
     let mutable number = accountNumber
     let mutable firstName = defaultArg first ""
     let mutable lastName = defaultArg last ""
     member this.AccountNumber
        with get() = number
        and set(value) = number <- value
     member this.FirstName
        with get() = firstName
        and set(value) = first_name <- value
     member this.LastName
        with get() = lastName
        and set(value) = lastName <- value
     member this.Balance
        with get() = balance
        and set(value) = balance <- value
     member this.Deposit(amount: float) = this.Balance <- this.Balance + amount
     member this.Withdraw(amount: float) = this.Balance <- this.Balance - amount
   
   
 let account1 = new Account(8782108, bal = 543.33,
                            FirstName="Raman", LastName="Iyer")

المنشئات ثابت أو نوع المنشئات

بالإضافة إلى تعيين تعليمات برمجية لإنشاء الكائنات ثابتة letو doيمكن أن يتم كتابة روابط في أنواع الفئة التي تقوم بتنفيذها قبل النوع هو أول المستخدم لإجراء تهيئة في المستوى النوع. للمزيد من المعلومات، راجع ترك للربط في فئات (F#) وقم بإجراء الربط في فئات (F#).

راجع أيضًا:

المبادئ

الأعضاء (F#)