摘要:(200-06-18) VB.NET 類別規劃
Webmod06.rarClass 類別
具有分類的意義
使用 "特徵" (Attribute) 分類
不使用功能分類Method * Method 程序 ( 行為或功能 )
如用功能分會有可能沒辦法在集合內 (如:電話(接,聽) 網路電話[不等於電話])
Method "飛"<--- 抽象描述(超人飛,鳥飛)
例: Employee(員工)[原型]--->工程師 , 業務員
類別
Namespace Domain.IT
'public Modifier修飾詞-可見度
'編譯產生父類別為System.Object
Public Class Employee
'類別層級變數(Data Field)
Private _id As String
Private _name As String
'實現封裝特性(private 私用 -可見度限這一個類別內)
Private _salary As Decimal
Private _birthDate As DateTime
Private _sex As String
' 編譯產生預設建構子 空參數
'屬性存取(程序)
Public Property Salary() As Decimal
Get
Return _salary
End Get
Set(ByVal value As Decimal)
If (value > 0) Then
_salary = value
End If
End Set
End Property
Public Property Id() As String
Get
Return Me._id
End Get
Set(ByVal value As String)
Me._id = value
End Set
End Property
Public Property Name() As String
Get
Return Me._name
End Get
Set(ByVal value As String)
Me._name = value
End Set
End Property
Public Property BirthDate() As DateTime
Get
Return Me._birthDate
End Get
Set(ByVal value As DateTime)
If (value <= System.DateTime.Now) Then
Me._birthDate = value
End If
End Set
End Property
Public Property Sex() As String
Get
Return Me._sex
End Get
Set(ByVal value As String)
Me._sex = value
End Set
End Property
End Class
End Namespace
主程式
Imports mod06.Domain.IT
Module TestEmployee
'主程式
Public Sub Main()
'定義區域變數
Dim emp As Employee = Nothing
'建構物件Cosntructor
'= 將起始位址給 emp
emp = New Employee() '使用預設建構子(沒有寫編譯產生)
Dim emp2 As Employee = Nothing
emp2 = emp 'emp將位址複製一份給emp2 emp and emp2參考同一個員工物件
emp.id = "0001" '字串物件位址給id儲存
emp.name = "'eric"
''程序性思考(非物件思考)
'Dim s As Decimal = -10000
''If s > 0 Then
'' emp.salary = s
''End If
'Setter
emp.Salary = 10000
'屬性getter
Dim r As Decimal = emp.Salary
System.Console.WriteLine(r.ToString())
'呼叫員工繼承的Object功能
System.Console.WriteLine(emp.ToString())
End Sub
End Module
補充:類別層級變數一定有預設值
屬性 As 資料表的欄位
Property (屬性) 未用使不暫空間 等到使用時才動態載入 (Later Binding)
屬性 As 資料表欄位
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'陣列
Dim emp(3) As Employee
emp(0) = New Employee() With {.Id = "00001", .Name = "eric", .Salary = 10000, .Sex = "男性", .BirthDate = New DateTime(2000, 1, 1)}
emp(1) = New Employee() With {.Id = "00002", .Name = "linda", .Salary = 10000, .Sex = "女性", .BirthDate = New DateTime(2000, 1, 1)}
emp(2) = New Employee() With {.Id = "00003", .Name = "barry", .Salary = 10000, .Sex = "男性", .BirthDate = New DateTime(2000, 1, 1)}
emp(3) = New Employee() With {.Id = "00004", .Name = "Candy", .Salary = 10000, .Sex = "女性", .BirthDate = New DateTime(2000, 1, 1)}
'資料繫結
Me.GridView1.DataSource = emp
Me.GridView1.DataBind()
End Sub
End Class