Member function (phương thức) của class là hàm có định nghĩa/nguyên mẫu trong class definition, tương tự biến khác. Nó thao tác trên object của class mà nó là member, và truy cập được tất cả members của class cho object đó.
Ví dụ:
public void setLength(double len) { length = len; }
public void setBreadth(double bre) { breadth = bre; }
Ví dụ truy cập class member functions:
Ví dụ
using System;
namespace BoxApplication {
class Box {
private double length;
private double breadth;
private double height;
public void setLength(double len) { length = len; }
public void setBreadth(double bre) { breadth = bre; }
public void setHeight(double hei) { height = hei; }
public double getVolume() { return length * breadth * height; }
}
class Boxtester {
static void Main(string[] args) {
Box Box1 = new Box();
Box Box2 = new Box();
double volume;
Box1.setLength(8.0);
Box1.setBreadth(9.0);
Box1.setHeight(7.0);
Box2.setLength(18.0);
Box2.setBreadth(20.0);
Box2.setHeight(17.0);
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
Kết quả
Volume of Box1 : 504
Volume of Box2 : 6120
Member variables (biến thành viên) là thuộc tính của object (góc độ thiết kế) và để private để triển khai encapsulation. Chỉ truy cập qua public member functions.
length và width là member variables vì mỗi instance Rectangle mới tạo instance mới của biến này:
Ví dụ
using System;
namespace RectangleApplication {
class Rectangle {
// member variables
private double length;
private double width;
public void Acceptdetails() {
length = 10;
width = 14;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
Kết quả
Length: 10
Width: 14
Area: 140