سلام درود خدمت همراهان همیشگی سایت پی وی لرن . با آموزش زبان برنامه نویسی #F همراهتون هستیم. Delegates در #F یک متغیر نوع مرجع یا reference است که مرجع را برای یک متد نگه می دارد. در این قسمت به نحوه اعلان Delegates در #F خواهیم پرداخت.
همونطور که بیان شد، Delegates در #F یک متغیر نوع مرجع یا reference هستند که مرجع را برای یک متد نگه می دارد. reference را می توان در زمان اجرا تغییر داد. delegates #F مشابه اشاره گرها به توابع، در C یا ++ C هستند.
اعلان Delegates، روش هایی را که می تواند توسط Delegates قابل اشاره باشد، تعیین می کند. یک Delegates می تواند به روشی اشاره کند، که همان signature را به عنوان Delegates دارد.
1 | type delegate-typename = delegate of type1 -> type2 |
به عنوان مثال، Delegates ها را در نظر بگیرید.
1 2 3 4 5 | // Delegate1 works with tuple arguments. type Delegate1 = delegate of (int * int) -> int // Delegate2 works with curried arguments. type Delegate2 = delegate of int * int -> int |
هر دو delegates می توانند برای ارجاع هر متدی که دارای دو پارامتر int باشند و یک متغیر نوع int را برمی گرداند استفاده می شود.
سینتکس
لطفا توجه داشته باشید
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | type Myclass() = static member add(a : int, b : int) = a + b static member sub (a : int) (b : int) = a - b member x.Add(a : int, b : int) = a + b member x.Sub(a : int) (b : int) = a - b // Delegate1 works with tuple arguments. type Delegate1 = delegate of (int * int) -> int // Delegate2 works with curried arguments. type Delegate2 = delegate of int * int -> int let InvokeDelegate1 (dlg : Delegate1) (a : int) (b: int) = dlg.Invoke(a, b) let InvokeDelegate2 (dlg : Delegate2) (a : int) (b: int) = dlg.Invoke(a, b) // For static methods, use the class name, the dot operator, and the // name of the static method. let del1 : Delegate1 = new Delegate1( Myclass.add ) let del2 : Delegate2 = new Delegate2( Myclass.sub ) let mc = Myclass() // For instance methods, use the instance value name, the dot operator, // and the instance method name. let del3 : Delegate1 = new Delegate1( mc.Add ) let del4 : Delegate2 = new Delegate2( mc.Sub ) for (a, b) in [ (400, 200); (100, 45) ] do printfn "%d + %d = %d" a b (InvokeDelegate1 del1 a b) printfn "%d - %d = %d" a b (InvokeDelegate2 del2 a b) printfn "%d + %d = %d" a b (InvokeDelegate1 del3 a b) printfn "%d - %d = %d" a b (InvokeDelegate2 del4 a b) |
هنگامی که شما برنامه را کامپایل و اجرا می کنید، خروجی زیر را تولید می کند.
1 2 3 4 5 6 7 8 | 400 + 200 = 600 400 - 200 = 200 400 + 200 = 600 400 - 200 = 200 100 + 45 = 145 100 - 45 = 55 100 + 45 = 145 100 - 45 = 55 |
delegates در #F مشابه اشاره گرها به توابع، در C یا ++ C هستند. در این قسمت از آموزش به نحوه اعلان Delegates در #F پرداختیم.