[技術類 - C# 學習誌 - C#面試考題 ] 建構式(Constructor)、this 關鍵字、遞迴、ArrayList
• 建構式(Constructor)
– 建構式在類別實體物件建立前即會執行,用來初始化物件
– 建構式的名稱一定要和類別名稱一樣
– 建構式與方法相同允許多載
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
car a = new car(3,5);
}
}
class car
{
public int showID()
{
}
public int id;
public int speed;
public car(int id,int speed) //這是建構式(Constructor),
{
this.id = id; //this 不能用在STATIC裡面
this.speed = speed;
}
public void accelerate(int x)
{
this.speed++;
}
public static void findcar()
{
}
}
}
——————————————————————————————————
• 遞迴是一種本身呼叫自己的方法
• 利用遞迴可以提供較為簡潔的方法進行數學運算
• 遞迴程式中,必須撰寫令遞迴結束執行的程式碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
}
class math
{
//遞迴:遞迴是一種本身呼叫自己的方法
//利用遞迴可以提供較為簡潔的方法進行數學運算
//遞迴程式中,必須撰寫令遞迴結束執行的程式碼
//sum(1~x)
//sum(x)=x+sum(x-1)
//sum(1)=1;
public static int sum(int x)
{
if (x == 1)
return 1;
return sum(x – 1) + x;
}
}
}
——————————————————————————————————
• ArrayList 概念
• 使用陣列時我們必須先設定好陣列的大小才可以使用,相當不方便
• ArrayList 屬於集合,集合大小會隨資料量大小動態改變
• 命名空間: System.Collections;
• 常用屬性: Count–實際包含的元素個數
• 常用方法
– Add–將物件加入至末端
– Insert–將物件插入至指定位置
– Remove–移除第一個符合指定物件的元素
– Clear–清除所有元素
– Sort–以遞增方式排序元素
– Reverse–將元素次序反轉
• 常用屬性: Count–實際包含的元素個數
• 常用方法
– Add–將物件加入至末端
– Insert–將物件插入至指定位置
– Remove–移除第一個符合指定物件的元素
– Clear–清除所有元素
– Sort–以遞增方式排序元素
– Reverse–將元素次序反轉
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ArrayList myAL = new ArrayList();
car myCar = new car(10);
myAL.Add(12);
myAL.Add(“ives");
myAL.Add(myCar);
Console.WriteLine(“myAL[{0}]︰{1}", 0, myAL[0]);
Console.WriteLine(“myAL[{0}]︰{1}", 1, myAL[1]);
Console.WriteLine(“myAL[{0}]︰{1}", 2, ((car)myAL[2]).id);
((car)myAL[2]).id = 100;
Console.WriteLine(“myCar︰" + myCar.id);
}
}
class car
{
public car(int x)
{
id = x;
}
public int id;
}
}
——————————————————————————————————
• ArrayList 練習:
• 請使用者輸入正整數資料(不限筆數)
• 當使用者輸入為負數停止
• 將使用者輸入的資料排序後列印至螢幕
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ArrayList myAL = new ArrayList();
while (true) //不確定使用者會輸入幾個正整數,因此用while
{
int x = int.Parse(Console.ReadLine());
if (x > 0)
myAL.Add(x);
else
break; //輸入負數就跳出
}
myAL.Sort(); //ArrayList 排序
foreach (int x in myAL)
{
Console.WriteLine(x); //印出ArrayList
}
Console.ReadLine();
}
}
}

用LINE分享給朋友:
這篇文章的QR CODE:(用手機掃我)