.NET Logo
Welcome Guest Search | Active Topics | Members | Log In | Register

การใช้งาน mutable , ref type Options · View
paedotnet
Posted: Thursday, October 02, 2008 12:56:16 AM

Rank: มือเทพ
Groups: Member

Joined: 12/6/2007
Posts: 344
Location: bkk

การใช้งาน Mutable
ปกติแล้วเราจะสร้างตัวแปรจะต้องใช้ keyword คำว่า let แล้วตามด้วยชื่อตัวแปร ซึ่งจะเหมือนกับการ
สร้างตัวแปรโดยใช้ keyword  mutable แต่จะต่างกันที่ การสร้างตัวแปร แบบ mutable นี้ค่าของ
ตัวแปรเราสามารถที่จะเปลี่ยนได้ตลอด และเราจะใช้ <- สำหรับการเปลื่ยนแปลงค่าหรือเพิ่มค่าเข้าไป(append)
ตัวอย่างการใช้งาน mutable

#light
let mutable a = "What is your name?" //สร้างตัวแปรแบบ mutable
printfn "%s" a //แสดงค่า a
a <- " John " //เพื่อค่าเข้าไปที่ตัวแปร a
printfn "%s" a
System.Console.ReadKey(true)


ผลลัพธ์แสดงดังรูป

การสร้าง mutable สำหรับข้อมูลชนิด Record

#light
type Member = {Id : int ; mutable Name_Lastname : string ; Age : int }
let SetMember = {Id = 1 ; Name_Lastname = "John shavwer" ; Age = 20}
let ShowFunction() =
 SetMember.Name_Lastname <- "Jame Scarlaz";
 printfn "%d" SetMember.Id
 printfn "%s" SetMember.Name_Lastname
 printfn "%d" SetMember.Age
ShowFunction()
System.Console.ReadKey(true)

ผลลัพธ์แสดงดังรูป

การใช้งาน ref keyword
  ref เป็นชนิดข้อมุลอย่างหนึ่งคล้ายๆกับ mutable นั้นคือสามารถที่จะ update ข้อมุลได้โดย ref นี้
จะประกอบไปด้วย 2 ส่วนหลักๆคือ Exclamation point หรือ ! และ Equal sign หรือ :=
โดย ! จะเป็นการกำหนดข้อมูล ส่วน := จะเป็นการ update ข้อมูล
ตัวอย่างการใช้งาน ref

#light
let number() =
 let array = [1;2;3;4]
 let i = ref 0 //กำหนด reference
 for a in array do
  i := !i + a
  printf "%d\n" !i
number()
System.Console.ReadLine()

 

 



[With great power comes great responsibility]
Users browsing this topic
Guest


Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Main Forum RSS : RSS

YAFVision Theme Created by Jaben Cargman (Tiny Gecko)
Powered by Yet Another Forum.net version 1.9.1.8 (NET v2.0) - 3/29/2008
Copyright © 2003-2008 Yet Another Forum.net. All rights reserved.


Sponsored by