การใช้งาน ทางด้าน properties
Scalar properties คือ properties ที่ทำหน้าที่อ่านข้อมูลและเขียนข้อมูล
รูปแบบ
การสร้าง properties แบบ อ่านและเขียน
property property_type property_name
{
property_type get() { คำสั่ง }
void set (property_type value) { คำสั่ง };
}
การกำหนดค่าอย่างเดียว
property property_type property_name
{
void set (property_type value) { คำสั่ง };
}
การอ่านค่า
property property_type property_name{
property_type get() { คำสั่ง };
}
ตัวอย่าง การใช้งาน Scalar properties
#include "stdafx.h"
using namespace System;
ref class TestScalarProperties{
private:
int value;
public:
property int Value{
int get(){
return value;
}
void set(int value){
this->value=value;
}
}
void Show(){
Console::WriteLine("Value is "+Value);
}
};
void main(){
TestScalarProperties^ t = gcnew TestScalarProperties();
t->Value= 100;
t->Show();
Console::ReadLine();
}
การใช้งาน Trivial Properties
Trivial properties จะคล้ายๆกับการประกาศตัวแปรซึ่งมีรูปแบบดังนี้
#include "stdafx.h"
using namespace System;
ref class TestScalarProperties{
private:
int value;
public:
property int Value; //กำหนด Trivial Properties
void Show(){
Console::WriteLine("Value is "+Value);
}
};
void main(){
TestScalarProperties^ t = gcnew TestScalarProperties();
t->Value=9999;
t->Show();
Console::ReadLine();
}
การใช้งาน Static Properties
เป็น properties ที่ประกาศเป็น Static
รูปแบบ
property static property_type property_name{
property_type get() { คำสั่ง };
void set (property_type value){ คำสั่ง };
}
เราสามารถเรียนใช้ Static Properties ผ่านชื่อคลาสได้เลยไม่ต้องเรียกผ่าน object
ตัวอย่าง
#include "stdafx.h"
using namespace System;
ref class TestScalarProperties{
private:
static String^ str; //ประกาศตัวแปรที่เป็น static สำหรับใช้กับ Static Properties
public:
property static String^ Value{ //สร้าง Static Properties
String^ get(){
return str;
}
void set(String^ value){
str=value;
}
}
};
void main(){
TestScalarProperties::Value = "Hello C++/CLI";
Console::WriteLine(TestScalarProperties::Value);
Console::ReadLine();
}
การใช้งาน Array Properties
เป็นการกำหนด properties แบบ อาร์เรย์
รูปแบบ
property array<property_type>^ property_name{
array<property_type>^ get() { คำสั่ง };
void set(array<property_type>^ value) { คำสั่ง };
}
ตัวอย่าง
#include "stdafx.h"
using namespace System;
ref struct TestArrayProperties{
private:
array<int>^ number;
public:
TestArrayProperties(int size){
number = gcnew array<int>(size);
}
property array<int>^ Number{
array<int>^ get(){
return number;
}
void set(array<int>^ value){
number =value;
}
}
};
void main(){
TestArrayProperties t(3);
t.Number[0] = 10;
t.Number[1] = 20;
t.Number[2] = 30;
Console::WriteLine(t.Number[0]+" "+t.Number[1]+" "+t.Number[2]);
Console::ReadLine();
}
[With great power comes great responsibility]