Olympic - Euro 2012, Movie Online, Tools, Info Tech, Programing, Sport. Make Money, Ebooks
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Wednesday, August 15, 2012
Sunday, August 12, 2012
Ebook Programing C#...Hot
This is ebook introduction you programing C#
Downloal here ebookC#
Downloal here ebookC#
Sunday, July 29, 2012
[Tutorial] Send/Receive Mail Using SMTP/POP3 In C #
Xây dựng lớp SMTP – dùng để gửi mail
1. Các thuộc tính cần có của một bức thư (mail):
- Danh sách người nhận.
// Danh sách người nhận
private string[] _DanhSachNguoiNhan;
public string[] DanhSachNguoiNhan
{
get { return _DanhSachNguoiNhan; }
set { _DanhSachNguoiNhan = value; }
}
Danh sách Bcc.
// Danh sách Bcc
private string[] _DanhSachBcc;
public string[] DanhSachBcc
{
get { return _DanhSachBcc; }
set { _DanhSachBcc = value; }
}
Danh sách Cc.
// Danh sách Cc
private string[] _DanhSachCc;
public string[] DanhSachCc
{
get { return _DanhSachCc; }
set { _DanhSachCc = value; }
}
- Danh sách file attachment (đính kèm).
// Danh sách file đính kèm
private Attachment[] _DanhSachAttment;
public Attachment[] DanhSachAttment
{
get { return _DanhSachAttment; }
set { _DanhSachAttment = value; }
}
Subject (tiêu đề).
// Tiêu đề mail cần gửi
private string _Subject;
public string Subject
{
get { return _Subject; }
set { _Subject = value; }
}
Content (nội dung).
// Nội dung mail cần gửi
private string _Contents;
public string Contents
{
get { return _Contents; }
set { _Contents = value; }
}
Các công việc cần làm khi gửi mail
- Set danh sách người nhận.
public void setDanhSachNguoiNhan(string SendTo)// SendTo là danh sách người nhận truyền vào
{
if (SendTo == "")
{
MessageBox.Show("Bạn Chưa Nhập Địa Chỉ Một Người Nhận Nào", "Thông Báo");// nếu danh sách truyền vào trống thì thông báo
return;
}
DanhSachNguoiNhan = SendTo.Split(',');// tách các người nhận bằng dấu ",";
}
Set danh sách Cc.
public void setDanhSachCc(string Cc)
{
if (Cc != "")
{
DanhSachCc = Cc.Split(',');
}
}
Tương tự set danh sách Bcc.
- Set danh sách file đính kèm.
public void setDanhSachAttachment(string[] AttachmentPath)
{
DanhSachAttment = new Attachment[AttachmentPath.Length];
for (int i = 0; i < AttachmentPath.Length; i++)
DanhSachAttment[i] = new Attachment(AttachmentPath[i]);
}
Sau khi đã lấy đủ thông tin cần thiết, ta thực hiện gửi mail. Trong C# có hai namespace hỗ trợ việc gửi mail bằng smtp là:
using System.Net.Sockets;
using System.Net.Mail;
Hàm thực hiện việc gửi mail:
+ Tạo kết nối tới server: (ở đây mình làm là Gmail, tương tự các bạn có thể làm với Yahoo Mail,…)
SmtpClient SmtpServer = new SmtpClient();
SmtpServer.Credentials = new System.Net.NetworkCredential(user.TenTaiKhoan, user.MatKhau);
SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;
Tạo một mail:
MailMessage smail = new MailMessage();
smail.From = new MailAddress(user.TenTaiKhoan, user.TenHienThi, System.Text.Encoding.UTF8);
Byte i;
for (i = 0; i < DanhSachNguoiNhan.Length; i++)
smail.To.Add(DanhSachNguoiNhan[i]);
if(DanhSachCc != null)
{
for (i = 0; i < DanhSachCc.Length; i++)
smail.CC.Add(DanhSachCc[i]);
}
if (DanhSachBcc != null)
{
for (i = 0; i < DanhSachBcc.Length; i++)
smail.Bcc.Add(DanhSachBcc[i]);
}
if (DanhSachAttment != null)
{
for (i = 0; i < DanhSachAttment.Length; i++)// danh sách file đính kèm (nếu có)
smail.Attachments.Add(DanhSachAttment[i]);
}
smail.Subject = Subject;
smail.Body = Contents;
smail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
Và gửi nó đi:
try
{
#region Tạo một bức thư điện tử
// Tạo một mail, phần code tạo một mail
#endregion
SmtpServer.Send(smail);
SmtpServer.Dispose();
return true;
}
catch
{ return false; }
*Chú thích : biến user.TenTaiKhoan và user.MatKhau là tên tài khoản và mật khẩu tài khoản gmail của bạn.
Vậy là xong lớp SMTP dùng để gửi mail. Bây giờ ta chỉ cần thiết kế một form gửi mail nữa là ok, các bạn lưu ý là nếu các bạn sử dụng code của mình thì chú thiết kế form cung cấp đủ các biến cho nó nhé!.
Bạn có thể vào đây:
http://www.mediafire.com/?eb4hk5buxj9898t
Bạn vào link trên để lấy class đó để bổ sung nhé!
1. Các thuộc tính cần có của một bức thư (mail):
- Danh sách người nhận.
// Danh sách người nhận
private string[] _DanhSachNguoiNhan;
public string[] DanhSachNguoiNhan
{
get { return _DanhSachNguoiNhan; }
set { _DanhSachNguoiNhan = value; }
}
Danh sách Bcc.
// Danh sách Bcc
private string[] _DanhSachBcc;
public string[] DanhSachBcc
{
get { return _DanhSachBcc; }
set { _DanhSachBcc = value; }
}
Danh sách Cc.
// Danh sách Cc
private string[] _DanhSachCc;
public string[] DanhSachCc
{
get { return _DanhSachCc; }
set { _DanhSachCc = value; }
}
- Danh sách file attachment (đính kèm).
// Danh sách file đính kèm
private Attachment[] _DanhSachAttment;
public Attachment[] DanhSachAttment
{
get { return _DanhSachAttment; }
set { _DanhSachAttment = value; }
}
Subject (tiêu đề).
// Tiêu đề mail cần gửi
private string _Subject;
public string Subject
{
get { return _Subject; }
set { _Subject = value; }
}
Content (nội dung).
// Nội dung mail cần gửi
private string _Contents;
public string Contents
{
get { return _Contents; }
set { _Contents = value; }
}
Các công việc cần làm khi gửi mail
- Set danh sách người nhận.
public void setDanhSachNguoiNhan(string SendTo)// SendTo là danh sách người nhận truyền vào
{
if (SendTo == "")
{
MessageBox.Show("Bạn Chưa Nhập Địa Chỉ Một Người Nhận Nào", "Thông Báo");// nếu danh sách truyền vào trống thì thông báo
return;
}
DanhSachNguoiNhan = SendTo.Split(',');// tách các người nhận bằng dấu ",";
}
Set danh sách Cc.
public void setDanhSachCc(string Cc)
{
if (Cc != "")
{
DanhSachCc = Cc.Split(',');
}
}
Tương tự set danh sách Bcc.
- Set danh sách file đính kèm.
public void setDanhSachAttachment(string[] AttachmentPath)
{
DanhSachAttment = new Attachment[AttachmentPath.Length];
for (int i = 0; i < AttachmentPath.Length; i++)
DanhSachAttment[i] = new Attachment(AttachmentPath[i]);
}
Sau khi đã lấy đủ thông tin cần thiết, ta thực hiện gửi mail. Trong C# có hai namespace hỗ trợ việc gửi mail bằng smtp là:
using System.Net.Sockets;
using System.Net.Mail;
Hàm thực hiện việc gửi mail:
+ Tạo kết nối tới server: (ở đây mình làm là Gmail, tương tự các bạn có thể làm với Yahoo Mail,…)
SmtpClient SmtpServer = new SmtpClient();
SmtpServer.Credentials = new System.Net.NetworkCredential(user.TenTaiKhoan, user.MatKhau);
SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;
Tạo một mail:
MailMessage smail = new MailMessage();
smail.From = new MailAddress(user.TenTaiKhoan, user.TenHienThi, System.Text.Encoding.UTF8);
Byte i;
for (i = 0; i < DanhSachNguoiNhan.Length; i++)
smail.To.Add(DanhSachNguoiNhan[i]);
if(DanhSachCc != null)
{
for (i = 0; i < DanhSachCc.Length; i++)
smail.CC.Add(DanhSachCc[i]);
}
if (DanhSachBcc != null)
{
for (i = 0; i < DanhSachBcc.Length; i++)
smail.Bcc.Add(DanhSachBcc[i]);
}
if (DanhSachAttment != null)
{
for (i = 0; i < DanhSachAttment.Length; i++)// danh sách file đính kèm (nếu có)
smail.Attachments.Add(DanhSachAttment[i]);
}
smail.Subject = Subject;
smail.Body = Contents;
smail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
Và gửi nó đi:
try
{
#region Tạo một bức thư điện tử
// Tạo một mail, phần code tạo một mail
#endregion
SmtpServer.Send(smail);
SmtpServer.Dispose();
return true;
}
catch
{ return false; }
*Chú thích : biến user.TenTaiKhoan và user.MatKhau là tên tài khoản và mật khẩu tài khoản gmail của bạn.
Vậy là xong lớp SMTP dùng để gửi mail. Bây giờ ta chỉ cần thiết kế một form gửi mail nữa là ok, các bạn lưu ý là nếu các bạn sử dụng code của mình thì chú thiết kế form cung cấp đủ các biến cho nó nhé!.
Bạn có thể vào đây:
http://www.mediafire.com/?eb4hk5buxj9898t
Bạn vào link trên để lấy class đó để bổ sung nhé!
Đo thời gian thực hiện chương trình C/C++/C#
Đo thời gian thực hiện chương trình C/C++/C# (Timer 4 newbie)
(Ngày cập nhật cuối: 30/3/2009)
Chủ đề bài báo: C/C++/C#
Trong các cuộc thi lập trình, các chương trình cài đặt các thuật toán cùng giải quyết một bài toán, chúng ta luôn có nhu cầu kiểm thử tốc độ thực hiện của các cài đặt bằng cách xem xét thời gian một đoạn chương trình hay một chương trình thực hiện là bao lâu. Trong bài báo nhỏ này, tôi xin cung cấp cách thức đo thời gian thực hiện của các chương trình được viết bằng các ngôn ngữ C/C++/C# trên DOS và trên Windows.
1. Đo thời gian thực hiện chương trình với ngôn ngữ C/C++ trên DOS
Đối với môi trường DOS chúng ta có thể dùng hàm clock() để đo thời gian thực hiện của chương trình cho cả chương trình viết bằng C và C++. Hàm clock() có khai báo nằm trong file header time.h, giá trị trả về của hàm là thời gian bắt đầu từ lúc chương trình chạy cho tới lúc gọi hàm, tính bằng số giây nhân với hằng số CLOCKS_PER_SEC, hằng số CLOCKS_PER_SEC có giá trị như CLK_TCK.
Ví dụ sau đo thời gian thực hiện của 600000000 vòng lặp rỗng:
// file timer4c.c
#include
#include
#include
int main( void )
{
long i = 600000000L;
clock_t start, finish;
double duration;
// Do thoi gian cua mot su kien
printf( “Thoi gian thuc hien %ld vong lap rong:”, i );
start = clock();
while( i– )
;
finish = clock();
duration = (double)(finish – start) / CLOCKS_PER_SEC;
printf( “%2.1f giay\n”, duration );
system(“pause”);
return 0;
}
2. Đo thời gian thực hiện chương trình với ngôn ngữ C trên Windows
Trên Windows chúng ta sử dụng hàm QueryPerformanceCounter(LARGE_INTEGER *) để thực hiện việc đo thời gian, hàm được khai báo trong file header windows.h. Hàm này có kiểu trả về là BOOL và trả về giá trị là thời gian tính bằng giây từ lúc chương trình bắt đầu chạy, tham số đầu vào là con trỏ tới một biến kiểu LARGE_INTEGER.
Ví dụ sau là chương trình đo thời gian thực hiện 600000000 vòng lặp rỗng:
// file timer4w.c
#include
#include
// khai bao cau truc va cac ham
typedef struct {
LARGE_INTEGER start;
LARGE_INTEGER stop;
} stopWatch;
void startTimer( stopWatch *timer) ;
void stopTimer( stopWatch *timer) ;
double LIToSecs( LARGE_INTEGER * L) ;
double getElapsedTime( stopWatch *timer);
void startTimer( stopWatch *timer)
{
QueryPerformanceCounter(&timer->start) ;
}
void stopTimer( stopWatch *timer)
{
QueryPerformanceCounter(&timer->stop) ;
}
double LIToSecs( LARGE_INTEGER * L)
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency( &frequency ) ;
return ((double)L->QuadPart /(double)frequency.QuadPart) ;
}
double getElapsedTime( stopWatch *timer) {
LARGE_INTEGER time;
time.QuadPart = timer->stop.QuadPart – timer->start.QuadPart;
return LIToSecs( &time) ;
}
// su dung cac ham
int main()
{
long i = 600000000L;
stopWatch timer;
double duration;
// Do thoi gian cua mot su kien
printf( “Thoi gian thuc hien %ld vong lap rong:”, i );
startTimer(&timer);
while( i– )
;
stopTimer(&timer);
duration = getElapsedTime(&timer);
printf( “%2.1f giay\n”, duration );
system(“pause”);
return 0;
}
3. Đo thời gian thực hiện của chương trình với C++ trên Windows
Tương tự như đối với chương trình C trên Windows, ở đây ta cũng sử dụng hàm QueryPerformanceCounter(LARGE_INTEGER *), tuy nhiên ta xây dựng lớp CStopWatch để tiện dùng cho các chương trình khác nhau.
// file timer4w.cpp
#include
#include
using namespace std;
typedef struct {
LARGE_INTEGER start;
LARGE_INTEGER stop;
} stopWatch;
// khai bao lop CStopWatch
class CStopWatch {
private:
stopWatch timer;
LARGE_INTEGER frequency;
double LIToSecs( LARGE_INTEGER & L) ;
public:
CStopWatch() ;
void startTimer( ) ;
void stopTimer( ) ;
double getElapsedTime() ;
};
double CStopWatch::LIToSecs( LARGE_INTEGER & L)
{
return ((double)L.QuadPart /(double)frequency.QuadPart) ;
}
CStopWatch::CStopWatch()
{
timer.start.QuadPart=0;
timer.stop.QuadPart=0;
QueryPerformanceFrequency( &frequency ) ;
}
void CStopWatch::startTimer( )
{
QueryPerformanceCounter(&timer.start) ;
}
void CStopWatch::stopTimer( )
{
QueryPerformanceCounter(&timer.stop) ;
}
double CStopWatch::getElapsedTime()
{
LARGE_INTEGER time;
time.QuadPart = timer.stop.QuadPart – timer.start.QuadPart;
return LIToSecs( time) ;
}
// su dung lop CStopWatch
int main()
{
long i = 600000000L;
CStopWatch timer;
double duration;
// Do thoi gian cua mot su kien
printf( “Thoi gian thuc hien %ld vong lap rong:”, i );
timer.startTimer();
while( i– )
;
timer.stopTimer();
duration = timer.getElapsedTime();
printf( “%2.1f giay\n”, duration );
system(“pause”);
return 0;
}
4. Đo thời gian thực hiện của chương trình với C#
Bắt đầu từ .NET Framework 2.0, lớp StopWatch được cung cấp cho người dùng để tiến hành các công việc liên quan tới đo đếm thời gian thực hiện 1 tác vụ nào đó, lớp này nằm trong namespace System.Diagnostics.
Ví dụ sau đây là chương trình đo thời gian thực hiện 600000000 vòng lặp rỗng:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace Timer
{
class Program
{
static void Main(string[] args)
{
Stopwatch st = new Stopwatch();
st.Start();
long i = 600000000L;
Console.WriteLine(“Thoi gian thuc hien {0} vong lap rong:”, i);
while (i > 0)
–i;
st.Stop();
Console.WriteLine(“{0} giay”, st.Elapsed.ToString());
if (Stopwatch.IsHighResolution)
Console.WriteLine(“Timed with Hi res”);
else
Console.WriteLine(“Not Timed with Hi res”);
Console.ReadKey();
}
}
}
5. Tài liệu tham khảo
1. MSDN 9.0, clock function (ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/dv_vccrt/html/3e1853dd-498f-49ba-b06a-f2315f20904e.htm).
2. http://cplus.about.com/od/howtodothingsin1/a/timing.htm
3. http://cplus.about.com/od/howtodothingsi2/a/timing.htm
4. http://cplus.about.com/od/howtodothingsinc/a/timing.htm
5. Microsoft® Windows® Internals, Fourth Edition: Microsoft Windows Server™ 2003, Windows XP, and Windows 2000, Mark E. Russinovich, David A. Solomon
Mặc dù đã hết sức thận trọng và xem xét kỹ lưỡng các ví dụ đưa ra trong bài viết, tuy vậy vẫn có thể không tránh khỏi các sai sót, rất mong nhận được sự đóng góp ý kiến của các bạn độc giả. Mọi góp ý, thắc mắc xin gửi về địa chỉ email:
nguyenvannam031@yahoo.com.vn
(Ngày cập nhật cuối: 30/3/2009)
Chủ đề bài báo: C/C++/C#
Trong các cuộc thi lập trình, các chương trình cài đặt các thuật toán cùng giải quyết một bài toán, chúng ta luôn có nhu cầu kiểm thử tốc độ thực hiện của các cài đặt bằng cách xem xét thời gian một đoạn chương trình hay một chương trình thực hiện là bao lâu. Trong bài báo nhỏ này, tôi xin cung cấp cách thức đo thời gian thực hiện của các chương trình được viết bằng các ngôn ngữ C/C++/C# trên DOS và trên Windows.
1. Đo thời gian thực hiện chương trình với ngôn ngữ C/C++ trên DOS
Đối với môi trường DOS chúng ta có thể dùng hàm clock() để đo thời gian thực hiện của chương trình cho cả chương trình viết bằng C và C++. Hàm clock() có khai báo nằm trong file header time.h, giá trị trả về của hàm là thời gian bắt đầu từ lúc chương trình chạy cho tới lúc gọi hàm, tính bằng số giây nhân với hằng số CLOCKS_PER_SEC, hằng số CLOCKS_PER_SEC có giá trị như CLK_TCK.
Ví dụ sau đo thời gian thực hiện của 600000000 vòng lặp rỗng:
// file timer4c.c
#include
#include
#include
int main( void )
{
long i = 600000000L;
clock_t start, finish;
double duration;
// Do thoi gian cua mot su kien
printf( “Thoi gian thuc hien %ld vong lap rong:”, i );
start = clock();
while( i– )
;
finish = clock();
duration = (double)(finish – start) / CLOCKS_PER_SEC;
printf( “%2.1f giay\n”, duration );
system(“pause”);
return 0;
}
2. Đo thời gian thực hiện chương trình với ngôn ngữ C trên Windows
Trên Windows chúng ta sử dụng hàm QueryPerformanceCounter(LARGE_INTEGER *) để thực hiện việc đo thời gian, hàm được khai báo trong file header windows.h. Hàm này có kiểu trả về là BOOL và trả về giá trị là thời gian tính bằng giây từ lúc chương trình bắt đầu chạy, tham số đầu vào là con trỏ tới một biến kiểu LARGE_INTEGER.
Ví dụ sau là chương trình đo thời gian thực hiện 600000000 vòng lặp rỗng:
// file timer4w.c
#include
#include
// khai bao cau truc va cac ham
typedef struct {
LARGE_INTEGER start;
LARGE_INTEGER stop;
} stopWatch;
void startTimer( stopWatch *timer) ;
void stopTimer( stopWatch *timer) ;
double LIToSecs( LARGE_INTEGER * L) ;
double getElapsedTime( stopWatch *timer);
void startTimer( stopWatch *timer)
{
QueryPerformanceCounter(&timer->start) ;
}
void stopTimer( stopWatch *timer)
{
QueryPerformanceCounter(&timer->stop) ;
}
double LIToSecs( LARGE_INTEGER * L)
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency( &frequency ) ;
return ((double)L->QuadPart /(double)frequency.QuadPart) ;
}
double getElapsedTime( stopWatch *timer) {
LARGE_INTEGER time;
time.QuadPart = timer->stop.QuadPart – timer->start.QuadPart;
return LIToSecs( &time) ;
}
// su dung cac ham
int main()
{
long i = 600000000L;
stopWatch timer;
double duration;
// Do thoi gian cua mot su kien
printf( “Thoi gian thuc hien %ld vong lap rong:”, i );
startTimer(&timer);
while( i– )
;
stopTimer(&timer);
duration = getElapsedTime(&timer);
printf( “%2.1f giay\n”, duration );
system(“pause”);
return 0;
}
3. Đo thời gian thực hiện của chương trình với C++ trên Windows
Tương tự như đối với chương trình C trên Windows, ở đây ta cũng sử dụng hàm QueryPerformanceCounter(LARGE_INTEGER *), tuy nhiên ta xây dựng lớp CStopWatch để tiện dùng cho các chương trình khác nhau.
// file timer4w.cpp
#include
#include
using namespace std;
typedef struct {
LARGE_INTEGER start;
LARGE_INTEGER stop;
} stopWatch;
// khai bao lop CStopWatch
class CStopWatch {
private:
stopWatch timer;
LARGE_INTEGER frequency;
double LIToSecs( LARGE_INTEGER & L) ;
public:
CStopWatch() ;
void startTimer( ) ;
void stopTimer( ) ;
double getElapsedTime() ;
};
double CStopWatch::LIToSecs( LARGE_INTEGER & L)
{
return ((double)L.QuadPart /(double)frequency.QuadPart) ;
}
CStopWatch::CStopWatch()
{
timer.start.QuadPart=0;
timer.stop.QuadPart=0;
QueryPerformanceFrequency( &frequency ) ;
}
void CStopWatch::startTimer( )
{
QueryPerformanceCounter(&timer.start) ;
}
void CStopWatch::stopTimer( )
{
QueryPerformanceCounter(&timer.stop) ;
}
double CStopWatch::getElapsedTime()
{
LARGE_INTEGER time;
time.QuadPart = timer.stop.QuadPart – timer.start.QuadPart;
return LIToSecs( time) ;
}
// su dung lop CStopWatch
int main()
{
long i = 600000000L;
CStopWatch timer;
double duration;
// Do thoi gian cua mot su kien
printf( “Thoi gian thuc hien %ld vong lap rong:”, i );
timer.startTimer();
while( i– )
;
timer.stopTimer();
duration = timer.getElapsedTime();
printf( “%2.1f giay\n”, duration );
system(“pause”);
return 0;
}
4. Đo thời gian thực hiện của chương trình với C#
Bắt đầu từ .NET Framework 2.0, lớp StopWatch được cung cấp cho người dùng để tiến hành các công việc liên quan tới đo đếm thời gian thực hiện 1 tác vụ nào đó, lớp này nằm trong namespace System.Diagnostics.
Ví dụ sau đây là chương trình đo thời gian thực hiện 600000000 vòng lặp rỗng:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace Timer
{
class Program
{
static void Main(string[] args)
{
Stopwatch st = new Stopwatch();
st.Start();
long i = 600000000L;
Console.WriteLine(“Thoi gian thuc hien {0} vong lap rong:”, i);
while (i > 0)
–i;
st.Stop();
Console.WriteLine(“{0} giay”, st.Elapsed.ToString());
if (Stopwatch.IsHighResolution)
Console.WriteLine(“Timed with Hi res”);
else
Console.WriteLine(“Not Timed with Hi res”);
Console.ReadKey();
}
}
}
5. Tài liệu tham khảo
1. MSDN 9.0, clock function (ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/dv_vccrt/html/3e1853dd-498f-49ba-b06a-f2315f20904e.htm).
2. http://cplus.about.com/od/howtodothingsin1/a/timing.htm
3. http://cplus.about.com/od/howtodothingsi2/a/timing.htm
4. http://cplus.about.com/od/howtodothingsinc/a/timing.htm
5. Microsoft® Windows® Internals, Fourth Edition: Microsoft Windows Server™ 2003, Windows XP, and Windows 2000, Mark E. Russinovich, David A. Solomon
Mặc dù đã hết sức thận trọng và xem xét kỹ lưỡng các ví dụ đưa ra trong bài viết, tuy vậy vẫn có thể không tránh khỏi các sai sót, rất mong nhận được sự đóng góp ý kiến của các bạn độc giả. Mọi góp ý, thắc mắc xin gửi về địa chỉ email:
nguyenvannam031@yahoo.com.vn
Monday, July 16, 2012
Polymorphism C#
This lesson teaches about Polymorphism in C#. Our objectives are as follows:
Another primary concept of object-oriented programming is Polymorphism. It allows you to invoke derived class methods through a base class reference during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won't necessarily have to be the same object type. However, if they're related by inheritance, you can add them to the array as the inherited type. Then if they all share the same method name, that method of each object can be invoked. This lesson will show you how to accomplish this.
using System;
public class DrawingObject
{ public virtual void Draw()
{
Console.WriteLine("I'm just a generic drawing object.");
}
}
Listing 9-1 shows the DrawingObject class. This will be the base class for other objects to inherit from. It has a single method named Draw(). The Draw() method has a virtual modifier. The virtual modifier indicates to derived classes that they can override this method. The Draw()method of the DrawingObject class performs a single action of printing the statement, "I'm just a generic drawing object.", to the console.
using System;
public class Line : DrawingObject
{ public override void Draw()
{
Console.WriteLine("I'm a Line.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Circle.");
}
}
public class Square : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Square.");
}
}
Listing 9-2 shows three classes. These classes inherit the DrawingObject class. Each class has a Draw() method and each Draw() method has an override modifier. The override modifier allows a method to override the virtual method of its base class at run-time. The override will happen only if the class is referenced through a base class reference. Overriding methods must have the same signature, name and parameters, as the virtual base class method it is overriding.
using System;
public class DrawDemo
{ public static int Main( )
{
DrawingObject[] dObj = new DrawingObject[4];
dObj[0] = new Line();
dObj[1] = new Circle();
dObj[2] = new Square();
dObj[3] = new DrawingObject();
foreach (DrawingObject drawObj in dObj)
{
drawObj.Draw();
}
return 0;
}
}
Listing 9-3 shows a program that uses the classes defined in Listing 9-1 and Listing 9-2. This program implements polymorphism. In the Main()method of the DrawDemo class, there is an array being created. The type of object in this array is the DrawingObject class. The array is nameddObj and is being initialized to hold four objects of type DrawingObject.
- Learn What Polymorphism Is.
- Implement a Virtual Method.
- Override a Virtual Method.
- Use Polymorphism in a Program.
Another primary concept of object-oriented programming is Polymorphism. It allows you to invoke derived class methods through a base class reference during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won't necessarily have to be the same object type. However, if they're related by inheritance, you can add them to the array as the inherited type. Then if they all share the same method name, that method of each object can be invoked. This lesson will show you how to accomplish this.
Listing 9-1. A Base Class With a Virtual Method: DrawingObject.cs
using System;
public class DrawingObject
{ public virtual void Draw()
{
Console.WriteLine("I'm just a generic drawing object.");
}
}
Listing 9-1 shows the DrawingObject class. This will be the base class for other objects to inherit from. It has a single method named Draw(). The Draw() method has a virtual modifier. The virtual modifier indicates to derived classes that they can override this method. The Draw()method of the DrawingObject class performs a single action of printing the statement, "I'm just a generic drawing object.", to the console.
Listing 9-2. Derived Classes With Override Methods: Line.cs, Circle.cs, and Square.cs
using System;
public class Line : DrawingObject
{ public override void Draw()
{
Console.WriteLine("I'm a Line.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Circle.");
}
}
public class Square : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Square.");
}
}
Listing 9-2 shows three classes. These classes inherit the DrawingObject class. Each class has a Draw() method and each Draw() method has an override modifier. The override modifier allows a method to override the virtual method of its base class at run-time. The override will happen only if the class is referenced through a base class reference. Overriding methods must have the same signature, name and parameters, as the virtual base class method it is overriding.
Listing 9-3. Program Implementing Polymorphism: DrawDemo.cs
using System;
public class DrawDemo
{ public static int Main( )
{
DrawingObject[] dObj = new DrawingObject[4];
dObj[0] = new Line();
dObj[1] = new Circle();
dObj[2] = new Square();
dObj[3] = new DrawingObject();
foreach (DrawingObject drawObj in dObj)
{
drawObj.Draw();
}
return 0;
}
}
Listing 9-3 shows a program that uses the classes defined in Listing 9-1 and Listing 9-2. This program implements polymorphism. In the Main()method of the DrawDemo class, there is an array being created. The type of object in this array is the DrawingObject class. The array is nameddObj and is being initialized to hold four objects of type DrawingObject.
Learn .NET and C# in 60 Days Lab 23(Day
Hoc .NET Tổng hợp tất cả các kiến thức mà bạn cần về C#
Class Inheritance C#
This lesson teaches about C# Inheritance. Our objectives are as follows:
Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective employment of reuse, you can save time in your programming.
using System;
public class ParentClass
{ public ParentClass()
{
Console.WriteLine("Parent Constructor.");
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class ChildClass : ParentClass
{ public ChildClass()
{
Console.WriteLine("Child Constructor.");
}
public static void Main()
{
ChildClass child = new ChildClass();
child.print();
}
}
Output:
Listing 8-1 shows two classes. The top class is named ParentClass and the main class is called ChildClass. What we want to do is create a child class, using existing code from ParentClass.
First we must declare our intention to use ParentClass as the base class of ChildClass. This is accomplished through the ChildClass declaration public class ChildClass : ParentClass. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name.
Note: C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multipleinterface inheritance, a subject covered in a later lesson.
ChildClass has exactly the same capabilities as ParentClass. Because of this, you can also say ChildClass "is" a ParentClass. This is shown in theMain() method of ChildClass when the print() method is called. ChildClass does not have its own print() method, so it uses the ParentClassprint() method. You can see the results in the 3rd line of output.
- Implement Base Classes.
- Implement Derived Classes.
- Initialize Base Classes from Derived Classes.
- Learn How to Call Base Class Members.
- Learn How to Hide Base Class Members.
Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective employment of reuse, you can save time in your programming.
Listing 8-1. Inheritance: BaseClass.cs
using System;
public class ParentClass
{ public ParentClass()
{
Console.WriteLine("Parent Constructor.");
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class ChildClass : ParentClass
{ public ChildClass()
{
Console.WriteLine("Child Constructor.");
}
public static void Main()
{
ChildClass child = new ChildClass();
child.print();
}
}
Output:
Parent Constructor. Child Constructor. I'm a Parent Class.
Listing 8-1 shows two classes. The top class is named ParentClass and the main class is called ChildClass. What we want to do is create a child class, using existing code from ParentClass.
First we must declare our intention to use ParentClass as the base class of ChildClass. This is accomplished through the ChildClass declaration public class ChildClass : ParentClass. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name.
Note: C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multipleinterface inheritance, a subject covered in a later lesson.
ChildClass has exactly the same capabilities as ParentClass. Because of this, you can also say ChildClass "is" a ParentClass. This is shown in theMain() method of ChildClass when the print() method is called. ChildClass does not have its own print() method, so it uses the ParentClassprint() method. You can see the results in the 3rd line of output.
Sunday, July 15, 2012
Control Statements - Loops C#
In the last lesson, you learned how to create a simple loop by using the goto statement. I advised you that this is not the best way to perform loops in C#. The information in this lesson will teach you the proper way to execute iterative logic with the various C# looping statements. Its goal is to meet the following objectives:
A while loop will check a condition and then continues to execute a block of code as long as the condition evaluates to a boolean value of true. Its syntax is as follows: while (<boolean expression>) { <statements> }. The statements can be any valid C# statements. The boolean expression is evaluated before any code in the following block has executed. When the boolean expression evaluates to true, the statements will execute. Once the statements have executed, control returns to the beginning of the while loop to check the boolean expression again.
When the boolean expression evaluates to false, the while loop statements are skipped and execution begins after the closing brace of that block of code. Before entering the loop, ensure that variables evaluated in the loop condition are set to an initial state. During execution, make sure you update variables associated with the boolean expression so that the loop will end when you want it to. Listing 4-1 shows how to implement a while loop.
Listing 4-1 shows a simple while loop. It begins with the keyword while, followed by a boolean expression. All control statements use boolean expressions as their condition for entering/continuing the loop. This means that the expression must evaluate to either a true or false value. In this case we are checking the myInt variable to see if it is less than (<) 10. Since myInt was initialized to 0, the boolean expression will return true the first time it is evaluated. When the boolean expression evaluates to true, the block immediately following the boolean expression will be executed.
- Learn the while loop.
- Learn the do loop.
- Learn the for loop.
- Learn the foreach loop.
- Complete your knowledge of the break statement.
- Teach you how to use the continue statement.
The while Loop
A while loop will check a condition and then continues to execute a block of code as long as the condition evaluates to a boolean value of true. Its syntax is as follows: while (<boolean expression>) { <statements> }. The statements can be any valid C# statements. The boolean expression is evaluated before any code in the following block has executed. When the boolean expression evaluates to true, the statements will execute. Once the statements have executed, control returns to the beginning of the while loop to check the boolean expression again.
When the boolean expression evaluates to false, the while loop statements are skipped and execution begins after the closing brace of that block of code. Before entering the loop, ensure that variables evaluated in the loop condition are set to an initial state. During execution, make sure you update variables associated with the boolean expression so that the loop will end when you want it to. Listing 4-1 shows how to implement a while loop.
Listing 4-1. The While Loop: WhileLoop.cs
using System;
class WhileLoop
{ public static void Main()
{ int myInt = 0;
while (myInt < 10)
{
Console.Write("{0} ", myInt);
myInt++;
}
Console.WriteLine();
}
}
Listing 4-1 shows a simple while loop. It begins with the keyword while, followed by a boolean expression. All control statements use boolean expressions as their condition for entering/continuing the loop. This means that the expression must evaluate to either a true or false value. In this case we are checking the myInt variable to see if it is less than (<) 10. Since myInt was initialized to 0, the boolean expression will return true the first time it is evaluated. When the boolean expression evaluates to true, the block immediately following the boolean expression will be executed.
Subscribe to:
Posts (Atom)