C#物件導向基礎練習-物件打包與接收
今天練習將物件打包一起傳出去,在運用規則上其實最需要注意的是種從關係,當A1呼叫物件method時,A1為主,若在method內需要使用到A2參數,則需要在method中的()內與相對應物件做連結,這樣會有2個主要步驟。
1.在物件中class類別裡的method()括號內為(classmate A2)(類別class名稱+物件object名稱),也就是需要接收的物件或資料。
public string talk(Classmate a2)
類別class 物件名稱
2.主程式則需呼叫者(A1)、呼叫者所呼叫的method的名稱(talk),method運作時所需接收的物件中class類別裡的參數(A2)。
MessageBox.Show(a1.talk(a2));
主 method 從
主程式程式碼:
private void button1_Click(object sender, EventArgs e)
{
Classmate a1 = new Classmate();
a1.name = "Wes Wang";
a1.major = "法律";
a1.clas = 2;
a1.grade = 4;
a1.id = 109001012;
Classmate a2 = new Classmate();
a2.name = "Maggie Chang";
a2.major = "音樂";
a2.clas = 1;
a2.grade = 4;
a2.id = 109006001;
MessageBox.Show(a1.introducea1());
MessageBox.Show(a2.introducea2());
MessageBox.Show("\r\n~~畢業前夕~~\r\n~~重大消息~~\r\n");
MessageBox.Show(a1.talk(a2)); ////*****本次重點
}
class架構的程式碼:
class Classmate
{
//property(int*3,str*2)
public int id, grade, clas;
public string name, major;
//method(introducea1、introducea2、talk)
public string introducea1()
{
return "你好!我叫" + name + ",我念" + major + "系,現在是" + grade + "年" + clas + "班;我的學號是" + id;
}
public string introducea2()
{
return "你好!我叫" + name + ",我念" + major + "系,現在是" + grade + "年" + clas + "班;我的學號是" + id;
}
public string talk(Classmate a2) ////*****本次重點
{
return major + "系" + grade + "年" + clas + "班的" + name + "與" + a2.major + "系" + a2.grade + "年" + a2.clas + "班的" + a2.name + "即將結婚了";
}
}
1.在物件中class類別裡的method()括號內為(classmate A2)(類別class名稱+物件object名稱),也就是需要接收的物件或資料。
public string talk(Classmate a2)
類別class 物件名稱
2.主程式則需呼叫者(A1)、呼叫者所呼叫的method的名稱(talk),method運作時所需接收的物件中class類別裡的參數(A2)。
MessageBox.Show(a1.talk(a2));
主 method 從
主程式程式碼:
private void button1_Click(object sender, EventArgs e)
{
Classmate a1 = new Classmate();
a1.name = "Wes Wang";
a1.major = "法律";
a1.clas = 2;
a1.grade = 4;
a1.id = 109001012;
Classmate a2 = new Classmate();
a2.name = "Maggie Chang";
a2.major = "音樂";
a2.clas = 1;
a2.grade = 4;
a2.id = 109006001;
MessageBox.Show(a1.introducea1());
MessageBox.Show(a2.introducea2());
MessageBox.Show("\r\n~~畢業前夕~~\r\n~~重大消息~~\r\n");
MessageBox.Show(a1.talk(a2)); ////*****本次重點
}
class架構的程式碼:
class Classmate
{
//property(int*3,str*2)
public int id, grade, clas;
public string name, major;
//method(introducea1、introducea2、talk)
public string introducea1()
{
return "你好!我叫" + name + ",我念" + major + "系,現在是" + grade + "年" + clas + "班;我的學號是" + id;
}
public string introducea2()
{
return "你好!我叫" + name + ",我念" + major + "系,現在是" + grade + "年" + clas + "班;我的學號是" + id;
}
public string talk(Classmate a2) ////*****本次重點
{
return major + "系" + grade + "年" + clas + "班的" + name + "與" + a2.major + "系" + a2.grade + "年" + a2.clas + "班的" + a2.name + "即將結婚了";
}
}
留言
張貼留言