Fields
รูปแบบในการประกาศ
public class Class1 { private string _field1; // รูปแบบที่ 1 double _field2; // รูปแบบที่ 2 public Class1() { int variable; // ตัวแปร ไม่ใช่ field } }แม้จะทำได้ แต่ก็ไม่ควรใช้รูปแบบที่ 2, ส่วนที่ประกาศใน method ไม่เรียกว่าเป็น field แต่เป็นตัวแปร (variable)
แบบฝึกหัด 1
- ให้เปิด file DeclareFields.cs ที่อยู่ใน Project CSL01_ClassElements_Fields
- หาบรรทัดที่เขียนว่า // TODO: Add your fields here
class DeclareFields { // TODO: Add your fields here }
- พิมพ์ fields ตามตารางด้านล่างเข้าไปในบรรทัดถัดจาก // TODO: Add your fields here
ชื่อ field | ชนิดข้อมูล (data type) | access modifier |
_firstName | string | private |
_lastName | string | - |
Birthdate | DateTime | protected |
_isMale | bool | private |
- ผลลัพธ์ควรได้ดังแสดงด้านล่าง
class DeclareFields { // TODO: Add your fields here private string _firstName; string _lastName; protected DateTime Birthdate; private bool _isMale; }
แบบฝึกหัด 2
- ให้เปิด file DeclareFieldsYourTurn.cs ที่อยู่ใน Project CSL01_ClassElements_Fields
- ให้ใส่ fields ตามตารางด้านล่างเข้าไปใน class ให้ถูกต้อง
ชื่อ field | ชนิดข้อมูล (data type) | access modifier |
_nameTitle | string | private |
_firstName | string | private |
_lastName | string | private |
_occupation | string | private |
_bloodType | char | private |
- แจ้งผู้ควบคุมเมื่อบันทึกเรียบร้อย
Download Source Code for the lab in Visual Studio 2010 format.
ไม่มีความคิดเห็น:
แสดงความคิดเห็น