.NET Programming - Nguyễn Đạt Thông 121 .NET Programming - Nguyễn Đạt Thông 122
Mảng đa chiều
Mảng jagged
(cid:1) Syntax:
(cid:1) A jagged array is an array of arrays
type[,] array_name;
type[, , , ,] array_name;
type[][] array_name;
type[][][[]] array_name;
(cid:1) Examples:
(cid:1) The elements of a jagged array can be of different dimensions and
sizes.
int[,] myRectArray = new int[2,3];
//3-row-2col array
int[,] myRectArray = new int[,] { {1,2}, {3,4}, {5,6}};
string[,] beatleName = { {"Lennon", "John"},
int[][] a = new int[3][];
a[0] = new int[4];
a[1] = new int[3];
a[2] = new int[1];
{"McCartney", "Paul"},
{"Harrison", "George"},
{"Starkey", "Richard"}
for (int i = 0; i < a.Length; i++)
{
};
for (int j = 0; j < a[i].Length; j++)
{
}
}
.NET Programming - Nguyễn Đạt Thông 123 .NET Programming - Nguyễn Đạt Thông 124
31
2/19/2014
Chuyển kiểu
Chuyển kiểu ngầm định
(cid:1) Many times, it’s necessary to convert instances of one type to
(cid:1) One type of data is automatically converted into another type of data.
another
(cid:2) Implicit Conversion
(cid:1) No data loss
(cid:2) Explicit Conversion
(cid:1) Implicit Numerical Conversion
long x;
int y = 25;
x = y; // implicit numerical conversion
(cid:1) Implicit Enumeration Conversion
(cid:2) Permit the decimal, integer, literal to be converted to any enumerate type
.NET Programming - Nguyễn Đạt Thông 125 .NET Programming - Nguyễn Đạt Thông 126
Chuyển kiểu ngầm định: tham chiếu
Chuyển kiểu tường minh
(cid:1) From any reference type to object.
(cid:1) Using the casting operator ()
(cid:1) From any class type D to any class type B,
(cid:1) May be loss data
(cid:2) provided D is inherited from B.
(cid:1) Explicit Numerical Conversions
(cid:1) From any class type A to interface type I,
(cid:2) provided A implements I.
int x = (int)26.45; // Explicit conversion
Console.WriteLine(x); // Displays only 26
(cid:1) From any interface type I2 to any other interface type I1,
(cid:1) Explicit Enumeration Conversions
(cid:2) provided I2 inherits I1.
(cid:2) From any enum type to sbyte, byte, short, ushort, int, uint, long,
ulong, char, float, double or decimal, and vice versa.
(cid:2) From any enum type to any other enum type
(cid:1) From any array type to System.Array.
(cid:1) From null to any reference type.
.NET Programming - Nguyễn Đạt Thông 127 .NET Programming - Nguyễn Đạt Thông 128
32
2/19/2014
Chuyển kiểu tường minh: tham chiếu
Boxing và Unboxing
(cid:1) From object to any reference type.
(cid:1) Boxing is conversion of a value type into a reference type.
(cid:1) From any class type B to any class type D,
(cid:2) provided B is the base class of D
(cid:1) Unboxing is the conversion of a reference type into a value type.
(cid:1) From any class type A to any interface type I,
(cid:2) provided A is not sealed and do not implement I.
(cid:1) From any interface type I to any class type A,
(cid:2) provided A is not sealed and implement I.
int x = 10;
object o1 = x;
// Implicit boxing
object o2 = (object)x; // Explicit boxing
int y = (int)o1;
// Unboxing
(cid:1) From any interface type I2 to any interface type I1,
(cid:2) provided I2 is not derived from I1.
(cid:1) From System.Array to any array type.
.NET Programming - Nguyễn Đạt Thông 129 .NET Programming - Nguyễn Đạt Thông 130
Kiểm tra trước khi chuyển kiểu
“Thử” chuyển kiểu
(cid:1) The is operator
(cid:1) The as operator
(cid:2) Checks if an object is compatible with a given type.
(cid:2) is used to perform conversions between compatible reference types.
(cid:2) evaluates to true if the provided expression is non-null, and the provided object
(cid:2) The as operator is like a cast operation. However, if the conversion is not
possible, as returns null instead of raising an exception.
can be cast to the provided type without causing an exception to be thrown.
(cid:2) only considers reference conversions, boxing conversions, and unboxing
conversions
.NET Programming - Nguyễn Đạt Thông 131 .NET Programming - Nguyễn Đạt Thông 132
33
2/19/2014
Tóm lược
Tham khảo thêm
(cid:1) How to create a program?
(cid:1) Tutorial: Hello World
http://msdn.microsoft.com/en-us/library/aa288463(v=vs.71).aspx
(cid:1) How to manipulate arguments?
(cid:1) How to control a program?
(cid:1) Tutorial: Command Line Parameters
http://msdn.microsoft.com/en-us/library/aa288457(v=vs.71).aspx
(cid:1) How to handle exceptions?
(cid:1) How to use console input/output?
(cid:1) Tutorial: Arrays
http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
(cid:1) How to use variables and constants?
(cid:1) Tutorial: Structures
(cid:1) How to use structures, enumerations, and arrays?
http://msdn.microsoft.com/en-us/library/aa288471(v=vs.71).aspx
(cid:1) How to convert between data types?
.NET Programming - Nguyễn Đạt Thông 133 .NET Programming - Nguyễn Đạt Thông 134
Tham khảo thêm
Tham khảo thêm
(cid:1) Tutorial: Getting Started
(cid:1) Types
http://www.csharp-station.com/tutorials/lesson01.aspx
http://msdn.microsoft.com/en-us/library/ms173104.aspx
(cid:1) Tutorial: Operators, Types, and Variables
(cid:1) Value Types
http://www.csharp-station.com/Tutorial/CSharp/Lesson02
http://msdn.microsoft.com/en-us/library/s1ax56ch(v=vs.71).aspx
(cid:1) Tutorial: Control Statements – Selection
(cid:1) Types Reference Tables
http://www.csharp-station.com/Tutorial/CSharp/Lesson03
http://msdn.microsoft.com/en-us/library/1dhd7f2x(v=vs.71).aspx
(cid:1) Tutorial: Control Statements – Loops
(cid:1) Arrays
http://www.csharp-station.com/Tutorial/CSharp/Lesson04
http://msdn.microsoft.com/en-us/library/aa287879(v=vs.71).aspx
.NET Programming - Nguyễn Đạt Thông 135 .NET Programming - Nguyễn Đạt Thông 136
34
2/19/2014
Tham khảo thêm
Ghi chú
(cid:1) Controlling program
http://en.wikibooks.org/wiki/C_Sharp_Programming/Control
(cid:1) Statements
http://msdn.microsoft.com/en-us/library/xt4z8b0f(v=vs.71).aspx
(cid:1) Casting and Type Conversions
http://msdn.microsoft.com/en-us/library/ms173105.aspx
(cid:1) Exceptions and Exception Handling
http://msdn.microsoft.com/en-us/library/ms173160.aspx
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
.NET Programming - Nguyễn Đạt Thông 137 .NET Programming - Nguyễn Đạt Thông 138
Lớp và Interface
Lớp trong C#
(cid:1) Classes are declared by using the keyword class
(cid:2) followed by the class name
(cid:2) and a set of class members surrounded by curly braces.
// Namespace Declaration
using System;
// Program start class
class Welcome
{
(cid:1) Classes & Objects
(cid:1) Constructors & Destructors
(cid:1) Constants & Fields
(cid:1) Methods, Properties & Indexers
(cid:1) Operators
(cid:1) Delegates & Events
(cid:1) Anonymous Methods
(cid:1) Nested Classes
// Main begins program execution.
static void Main()
{
// Write to console
Console.WriteLine("Welcome to C#");
}
}
(cid:1) Inheritance
(cid:1) Polymorphism
(cid:1) Abstract classes & Interfaces
(cid:1) Namespaces
.NET Programming - Nguyễn Đạt Thông 139 .NET Programming - Nguyễn Đạt Thông 140
35
2/19/2014
Thành phần của lớp
Đối tượng
(cid:1) Members which can be declared in a class:
(cid:1) Objects are instances or specific occurrences of a class.
(cid:2) Constructors, Destructors, Constants, Fields, Methods, Properties, Indexers,
Delegates, Events, Nested Classes.
(cid:1) Objects are created by new operator and referenced by variables of
reference types.
(cid:1) Members are accessed by “dot” operator.
(cid:1) Types of member
(cid:2) Instance class members:
Welcome w = new Welcome();
Customer c = new Customer();
Date d = new Date();
Button btn = new Button();
○ belong to a specific occurrence of a class.
○ be accessed through instances.
(cid:2) Static class members:
○ belong to that class.
○ be accessed through that class.
.NET Programming - Nguyễn Đạt Thông 141 .NET Programming - Nguyễn Đạt Thông 142
Lớp Static
Xác định mức độ truy xuất
(cid:1) A class can be declared static, indicating that it contains only
(cid:1) An access modifier determines how other parts of a program can
static members.
access a class member.
(cid:1) It is not possible to create instances of a static class using the new
(cid:1) Member access is controlled by four access modifiers:
keyword.
(cid:1) Static classes are sealed (cannot be inherited).
(cid:2) public,
(cid:2) private,
(cid:2) protected,
(cid:2) internal.
.NET Programming - Nguyễn Đạt Thông 143 .NET Programming - Nguyễn Đạt Thông 144
36
2/19/2014
Access Modifiers
Access Modifiers
(cid:1) A public member can be accessed by any other code in program.
(cid:1) The internal modifier declares that a member is known throughout
all files in an assembly,
(cid:2) but unknown outside that assembly.
(cid:1) A private member can be accessed only by other members of its
class.
(cid:1) The protected internal member (only class members) is
(cid:1) A protected member is public within a class hierarchy,
(cid:2) but private outside that hierarchy.
accessible
(cid:2) within its own assembly or
(cid:2) to derived types.
.NET Programming - Nguyễn Đạt Thông 145 .NET Programming - Nguyễn Đạt Thông 146
Constructors và Destructors
Hàm khởi động
(cid:1) Every class has at least one constructor,
(cid:1) Constructors are class methods that are executed when an object of
(cid:2) which is called automatically any time an instance of a class is created.
a given type is created.
(cid:1) The purpose of constructors is to initialize class members
(cid:1) Destructors are used to destruct instances of classes.
(cid:2) when an instance of the class is created.
(cid:1) Constructors do not have return values and always have the same
name as the class.
.NET Programming - Nguyễn Đạt Thông 147 .NET Programming - Nguyễn Đạt Thông 148
37
2/19/2014
Khởi động static
Khởi động mặc định
(cid:1) Static constructors are used to initialize static fields in a class.
(cid:1) A constructor that takes no parameters is called a default
constructor.
(cid:1) Declare a static constructor by using the keyword static just in
front of the constructor name.
(cid:1) Unless the class is static, classes without constructors are given a
public default constructor.
(cid:1) A static constructor is called
(cid:1) Default constructors could be overridden for class only.
(cid:2) before an instance of a class is created,
(cid:2) before a static member is called,
(cid:2) and before the static constructor of a derived class.
(cid:1) Static constructors are called only once.
.NET Programming - Nguyễn Đạt Thông 149 .NET Programming - Nguyễn Đạt Thông 150
Khởi động static: Ví dụ
Khởi động private
(cid:1) Private constructors are used to prevent a class from being
instantiated.
using System;
using System.Collections.Generic;
using System.Text;
using Samsung.Televison;
using Sony.Televison;
class Nlog
{
public class Bus {
// Static constructor:
static Bus() {
Console.WriteLine("The static constructor invoked.");
// Private Constructor:
private NLog()
{
}
}
public static void Drive() {
Console.WriteLine("The Drive method invoked.");
public static double e = System.Math.E;
//2.71828...
}
}
}
namespace FirstProgram {
class Program {
static void Main1() {
Bus.Drive();
Bus.Drive();
Console.ReadLine();
}
}
}
.NET Programming - Nguyễn Đạt Thông 151 .NET Programming - Nguyễn Đạt Thông 152
38
2/19/2014
Từ khóa this
Khởi động với tham số
(cid:1) Both classes and structures can define constructors that take
(cid:1) A constructor can invoke another constructor in the same object
(cid:2) using the this keyword.
parameters.
(cid:1) this can be used with or without parameters,
(cid:1) Classes and structures can also define multiple constructors.
(cid:2) and any parameters in the constructor are available as parameters to this.
public class Employee {
public int salary;
public class Employee {
// Constructor with 1 parameter
public Employee(int annualSalary) {
public int salary;
// Constructor with 1 parameter
public Employee(int annualSalary) {
salary = annualSalary;
salary = annualSalary;
}
}
// Constructor with 2 parameters
public Employee(int weeklySalary, int numberOfWeeks) :
// Constructor with 2 parameters
public Employee(int weeklySalary, int numberOfWeeks) {
salary = weeklySalary * numberOfWeeks;
this(weeklySalary * numberOfWeeks)
// invoke constructor with 1 parameter
}
{ }
}
}
.NET Programming - Nguyễn Đạt Thông 153 .NET Programming - Nguyễn Đạt Thông 154
Từ khóa base
Hàm dọn dẹp
(cid:1) A constructor can use the base keyword to call the constructor of a
(cid:1) Destructors cannot be defined in structures.
base class.
(cid:2) They are only used with classes.
(cid:1) The base keyword can be used with or without parameters.
(cid:1) A class can only have one destructor.
(cid:1) In a derived class,
(cid:1) Destructors cannot be inherited or overloaded.
(cid:2) if a base-class constructor is not called explicitly using the base keyword,
(cid:2) then the default constructor, if there is one, is called implicitly.
(cid:1) Destructors cannot be called.
(cid:2) They are invoked automatically.
.NET Programming - Nguyễn Đạt Thông 155 .NET Programming - Nguyễn Đạt Thông 156
39
2/19/2014
Hàm dọn dẹp
Ghi chú
(cid:1) A destructor does not take modifiers or have parameters.
(cid:1) The destructor implicitly calls Finalize on the object's base class.
class Employee {
~Employee() {
Console.WriteLine("Employee's destructor is called");
}
}
class TestDestructor {
static void Main() {
Employee t = new Employee();
}
}
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
.NET Programming - Nguyễn Đạt Thông 157 .NET Programming - Nguyễn Đạt Thông 158
Constants và Fields
Field
(cid:1) Fields are objects or values contained in a class or a structure.
(cid:1) Fields allow classes and structures to encapsulate data.
(cid:1) Constants are values (not objects, except string objects) which are
(cid:1) Fields should generally be private.
(cid:2) Access to fields by external classes should be indirect, by means of methods,
known at compile time and do not change.
properties, or indexers.
(cid:1) Fields are declared within the class block:
;
.NET Programming - Nguyễn Đạt Thông 159 .NET Programming - Nguyễn Đạt Thông 160
40
2/19/2014
Khai báo Field
Hằng số
(cid:1) Classes and structures can declare constants as members.
(cid:1) A field initialization cannot refer to other instance fields.
(cid:1) Constants are declared as a field, using the const keyword before
(cid:1) A field can optionally be declared static.
the type of the field.
(cid:2) This makes the field available to callers at any time, even if no instance of the
class exists.
(cid:1) Constants must be initialized as they are declared.
(cid:1) A field can be declared readonly.
(cid:1) Constants are accessed as if they were static fields,
(cid:2) A read-only field can only be assigned a value during initialization or in a
(cid:2) although they cannot use the static keyword.
constructor.
.NET Programming - Nguyễn Đạt Thông 161 .NET Programming - Nguyễn Đạt Thông 162
Constants và Fields: Ví dụ
Methods, Properties và Indexers
public class CalendarDate {
(cid:1) A method is a code block that contains a series of statements.
(cid:1) A property is a pair of set and get method.
public int month = 7; // declare a field and initialize it
public readonly int day = 29; // read-only field
public static readonly int year = 2011; // static read-only, MUST be initialized
public bool isNewYear = (day == 1 && month == 1);
// ERROR: cannot initialize a field from others
public bool isNewMelenium = (year % 1000 == 0);
// OK: can iniitialize a field from static ones
public CalendarDate() {
day = 30; // can be initialized at declaration or in constructor
year = 2012; // ERROR: allowed only in static constructor
(cid:1) Indexers enable objects to be indexed in a similar way to arrays.
}
}
class Calendar {
public const int months = 12; // declare a constant and MUST initialize it
public const int weeks = 52;
public const int days = 365;
public const double daysPerWeek = days / weeks;// initialize from other constants
public const double daysPerMonth = days / months;
}
class ConstantsAndFields {
static void Main1() {
CalendarDate birthday = new CalendarDate();
birthday.month = 7; // access fields through instances
birthday.month = Calendar.months; // access constants through the class
}
}
.NET Programming - Nguyễn Đạt Thông 163 .NET Programming - Nguyễn Đạt Thông 164
41
2/19/2014
Phương thức
Tham số
(cid:1) Methods are extremely useful
(cid:1) To the method being called, the incoming arguments are called
(cid:2) because they allow to separate your logic into different units.
(cid:1) Information can be passed to methods, one or more statements are
parameters.
(cid:2) Arguments: input values
(cid:2) Parameters: input variables
performed, and a value is returned.
(cid:1) Method parameters
(cid:1) The capability to pass parameters and return values is optional
(cid:2) and depends on what the method is going to do.
(cid:2) are enclosed in parentheses
(cid:2) and are separated by commas.
(cid:1) Empty parentheses indicate that the method requires no parameters.
.NET Programming - Nguyễn Đạt Thông 165 .NET Programming - Nguyễn Đạt Thông 166
Giá trị trả về
Signature của phương thức
(cid:1) Method can return the value using the return keyword.
(cid:1) Method signatures contains
(cid:1) If the method is a void type, the return statement can be omitted.
(cid:1) Methods with a non-void return type are required to use the return
(cid:2) Access level (public, private, etc.)
(cid:2) Access modifier (abstract, sealed, etc.)
(cid:2) Return value
(cid:2) Method name
(cid:2) Method parameters
keyword to return a value.
.NET Programming - Nguyễn Đạt Thông 167 .NET Programming - Nguyễn Đạt Thông 168
42
2/19/2014
Từ khóa ref
Truyền tham số
(cid:1) When an object based on a reference type is passed to a method
(cid:1) The ref keyword causes arguments to be passed by reference.
(cid:2) Any changes made to the parameter in the method will be reflected in that
variable when control passes back to the calling method.
(cid:2) No copy of the object is made
(cid:2) Changes made through the reference will therefore be reflected in the calling
method.
(cid:1) To use a ref parameter,
(cid:2) both the method definition and the calling method must explicitly use the ref
keyword.
(cid:1) When a value type is passed to a method
(cid:2) A copy is passed instead of the object itself
(cid:2) Any changes made to the parameter have no effect within the calling method.
(cid:1) An argument passed to a ref parameter must first be initialized.
.NET Programming - Nguyễn Đạt Thông 169 .NET Programming - Nguyễn Đạt Thông 170
Từ khóa out
ref và out: Ví dụ
(cid:1) Similar to the ref keyword, the out keyword causes arguments to
struct StructSample {
public int i;
}
be passed by reference.
class RefExample {
static void RefMethod(ref StructSample s) {
s.i = 44;
(cid:1) The out does not requires that the variable be initialized before
}
static void OutMethod(out StructSample s) {
being passed.
s = new StructSample();
s.i = 11;
}
(cid:1) To use an out parameter,
static void Main() {
(cid:2) both the method definition and the calling method must explicitly use the out
keyword.
StructSample val_ref = new StructSample();
// default constructor: val_ref.i = 0;
RefMethod(ref val_ref); // "ref" is required here
// val_ref.i is now 44
StructSample val_out; // no initialization
OutMethod(out val_out); // "out" is required here
// val_out now point to new StructSample
}
}
.NET Programming - Nguyễn Đạt Thông 171 .NET Programming - Nguyễn Đạt Thông 172
43
2/19/2014
Từ khóa params
params: Ví dụ
public class MyClass {
static void UseIntParams(string str, params int[] list) {
(cid:1) The params keyword
Console.WriteLine(str);
for (int i = 0 ; i < list.Length; i++) {
Console.WriteLine(list[i]);
(cid:2) allows to specify a method parameter that takes an argument where the number
of arguments is variable.
}
Console.WriteLine();
}
static void UseObjectParams(params object[] list) {
for (int i = 0 ; i < list.Length; i++) {
(cid:1) No additional parameters are permitted after the params keyword in
Console.WriteLine(list[i]);
a method declaration
}
Console.WriteLine();
}
static void Main() {
(cid:1) Only one params keyword is permitted in a method declaration.
UseIntParams("Start", 1, 2, 3, 4, 5, 6, 7, 8, 9);
UseObjectParams(1, 'a', "Alphabe", true, new MyClass());
// An array of objects can also be
// passed, as long as the array type
// matches the method being called.
int[] myarray = new int[3] { 10, 11, 12 };
UseIntParams("Second", myarray);
}
}
.NET Programming - Nguyễn Đạt Thông 173 .NET Programming - Nguyễn Đạt Thông 174
Overload một phương thức
Thuộc tính – Properties
public class MyClass {
static void UseIntParams(string str, params int[] list) {
(cid:1) Properties enable a class to expose a public way of getting and
Console.WriteLine(str);
for (int i = 0 ; i < list.Length; i++) {
Console.WriteLine(list[i]);
}
Console.WriteLine();
setting values,
(cid:2) while hiding implementation or verification code.
}
static void UseObjectParams(params object[] list) {
for (int i = 0 ; i < list.Length; i++) {
(cid:1) A get accessor is used to return the property value,
Console.WriteLine(list[i]);
}
Console.WriteLine();
and a set accessor is used to assign a new value.
}
static void Main() {
(cid:1) The value keyword is used to define the value being assigned by
the set accessor.
UseIntParams("Start", 1, 2, 3, 4, 5, 6, 7, 8, 9);
UseObjectParams(1, 'a', "Alphabe", true, new MyClass());
// An array of objects can also be
// passed, as long as the array type
// matches the method being called.
(cid:1) Properties that do not implement a set accessor are read only.
int[] myarray = new int[3] { 10, 11, 12 };
UseIntParams("Second", myarray);
}
}
.NET Programming - Nguyễn Đạt Thông 175 .NET Programming - Nguyễn Đạt Thông 176
44
2/19/2014
Thuộc tính
Chỉ mục – Indexers
(cid:1) Syntax to define a property
(cid:1) Indexers enable objects to be indexed in a similar way to arrays.
{
(cid:1) Indexers can be indexed by an integer value or other values.
get { /* ... */ }
set { /* ... */ }
}
class TimePeriod {
(cid:1) Indexers can have more than one formal parameter,
(cid:2) for example, when accessing a two-dimensional array.
private double seconds;
public double Hours {
get { return seconds / 3600; }
set { seconds = value * 3600; } // "value" indicates the input
}
}
class Program {
static void Main() {
TimePeriod t = new TimePeriod();
t.Hours = 24; // "set" accessor is called
System.Console.WriteLine("Time in hours: " + t.Hours);
// "get" accessor is called
}
}
.NET Programming - Nguyễn Đạt Thông 177 .NET Programming - Nguyễn Đạt Thông 178
Truy xuất các thành phần get và set
Chỉ mục
(cid:1) Syntax to define an indexer
(cid:1) By default accessors have the same visibility, or access level
this[] {
(cid:2) that of the property or indexer to which they belong.
get { /* ... */ }
set { /* ... */ }
(cid:1) Accessor modifiers can be used only if the property or indexer has
}
class Sample {
private int[] arr = new int[100];
both set and get accessors.
(cid:2) In this case, the modifier is permitted on one only of the two accessors.
public int this[String s, int i] {
get { if (s == "Top") return arr[i]; else return 0; }
set { if (s == "Top") arr[i] = value; } // "value" indicates the input
}
}
class SampleProgram {
static void Main(string[] args) {
Sample intCol = new Sample();
intCol["Right", 0] = 7; // "set" accessor is called
System.Console.WriteLine("{0}", intCol["Top", 0]);
// "get" accessor is called
}
}
.NET Programming - Nguyễn Đạt Thông 179 .NET Programming - Nguyễn Đạt Thông 180
45
2/19/2014
Ghi chú
Toán tử
(cid:1) C# allows user-defined types to overload operators
(cid:2) by defining static member functions using the operator keyword.
(cid:1) Unary operators have one parameter,
and binary operators have two parameters.
(cid:1) One parameter must be the same type as the class or structure that
declares the operator.
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
.NET Programming - Nguyễn Đạt Thông 181 .NET Programming - Nguyễn Đạt Thông 182
Overload các toán tử
Toán tử: Ví dụ
(cid:1) The comparison operators, if overloaded, must be overloaded in
public struct Complex {
public int real;
public int imaginary;
// Constructor.
public Complex(int real, int imaginary) {
pairs
(cid:2) if == is overloaded, != must also be overloaded
(cid:2) similar for < and >, and for <= and >=.
this.real = real;
this.imaginary = imaginary;
}
Operators
Overload
+ - ! ~ ++ --
YES
// Specify which operator to overload (+),
// the types that can be added (two Complex objects),
// and the return type (Complex).
public static Complex operator +(Complex c1, Complex c2) {
+ - * / % & | ^ << >>
YES
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
== != < > <= >=
YES
&& || [] (T)x
NO
// Override the ToString() method to display a complex number
// in the traditional format:
public override string ToString() {
+= -= *= /= %= &= |= ^= <<= >>=
NO
return (System.String.Format("{0} + {1}i", real, imaginary));
}
}
NO
= . ?: ?? -> => f(x), as, checked,
unchecked, default, delegate, is, new,
sizeof, typeof
.NET Programming - Nguyễn Đạt Thông 183 .NET Programming - Nguyễn Đạt Thông 184
46
2/19/2014
Delegates và Events
Delegates
(cid:1) A delegate is a type that references a method.
(cid:1) Delegates are similar to C++ function pointers, but are type safe.
(cid:1) Once a delegate is assigned a method,
(cid:1) Events provide a way for a class or object to notify other classes or
(cid:2) it behaves exactly like that method.
objects when something of interest happens.
(cid:1) The delegate method can be used like any other method,
(cid:2) with parameters and a return value.
(cid:1) Any method
(cid:2) that matches the delegate's signature (do not need match exactly), which
consists of the return type and parameters,
(cid:2) can be assigned to the delegate.
.NET Programming - Nguyễn Đạt Thông 185 .NET Programming - Nguyễn Đạt Thông 186
Delegates
Covariance và Contravariance
(cid:1) Delegates are similar to C++ function pointers, but are type safe.
(cid:1) Covariance and contravariance provide a degree of flexibility
(cid:2) when matching method signatures with delegate types.
(cid:1) Delegates allow methods to be passed as parameters.
(cid:1) Covariance permits a method
(cid:1) Delegates can be used to define callback methods.
(cid:2) to have a more derived return type than what is defined in the delegate.
(cid:1) Delegates can be chained together;
(cid:1) Contravariance permits a method
(cid:2) for example, multiple methods can be called on a single event.
(cid:2) with parameter types that are less derived than in the delegate type.
.NET Programming - Nguyễn Đạt Thông 187 .NET Programming - Nguyễn Đạt Thông 188
47
2/19/2014
Covariance: Ví dụ
Contravariance: Ví dụ
class Mammals { }
class Mammals { }
class Dogs : Mammals { }
class Dogs : Mammals { }
class MyProgram {
class Program {
// Define the delegate: accept a "Dog" and return nothing
public delegate void HandlerMethod(Dogs d);
// Define the delegate: no parameter and return a "Mammal"
public delegate Mammals HandlerMethod();
// method 1 return a "Mammal"
public static Mammals FirstHandler() {
// method 1 receive a "Mammal"
// if a "Dog" is passed, it works fine since a "Dog" is also a "Mammal"
public static void FirstHandler(Mammals m) {
return null;
return;
}
}
// method 2 return a "Dog" which is also a "Mammal"
public static Dogs SecondHandler() {
// method 2 receive a "Dog"
public static void SecondHandler(Dogs d) {
return null;
return;
}
}
static void Main() {
static void Main1() {
// signature of method 1 is exactly matched with delegate
HandlerMethod handler1 = FirstHandler;
// Contravariance allows this delegate.
HandlerMethod handler1 = FirstHandler;
// Covariance allows this delegate.
HandlerMethod handler2 = SecondHandler;
// signature of method 2 is exactly matched with delegate
HandlerMethod handler2 = SecondHandler;
}
}
}
}
.NET Programming - Nguyễn Đạt Thông 189 .NET Programming - Nguyễn Đạt Thông 190
Sự kiện – Events
Events
(cid:1) Events provide a way for a class or object
(cid:1) An event can have multiple subscribers.
(cid:2) A subscriber can handle multiple events from multiple publishers.
(cid:2) to notify other classes or objects
(cid:2) when something of interest happens.
(cid:1) Events that have no subscribers are never called.
(cid:1) The class that sends (or raises) the event is called the publisher and
the classes that receive (or handle) the event are called subscribers.
(cid:1) Events are commonly used to signal user actions
(cid:2) such as button clicks or menu selections in graphical user interfaces.
(cid:1) The publisher determines when an event is raised;
the subscribers determine what action is taken.
(cid:1) When an event has multiple subscribers,
(cid:2) the event handlers are invoked synchronously.
.NET Programming - Nguyễn Đạt Thông 191 .NET Programming - Nguyễn Đạt Thông 192
48
2/19/2014
Events: Ví dụ
Phương thức Anonymous
(cid:1) In versions of C# before 2.0,
// Declare the delegate
public delegate void SampleEventHandler(object sender, SampleEventArgs e);
public class Publisher {
(cid:2) the only way to declare a delegate was to use named methods.
// Declare the event.
public event SampleEventHandler SampleEvent;
// Wrap the event in a protected virtual method
protected virtual void RaiseSampleEvent() {
(cid:1) C# 2.0 introduced anonymous methods.
// Raise the event
SampleEvent(this, new SampleEventArgs("Hello"));
}
}
public class Subscriber {
(cid:1) In C# 3.0 and later, lambda expressions supersede anonymous
void HandleSampleEvent(object sender, SampleEventArgs a) {
// Do something useful here.
methods as the preferred way to write inline code.
}
public void subcribe() {
Publisher publisher = new Publisher();
// subscribe to the event
publisher.SampleEvent += new SampleEventHandler(HandleSampleEvent); // C# 1.0
publisher.SampleEvent += HandleSampleEvent; // C# 2.0
// unsubscribe from the event
publisher.SampleEvent -= HandleSampleEvent;
}
}
.NET Programming - Nguyễn Đạt Thông 193 .NET Programming - Nguyễn Đạt Thông 194
Sử dụng phương thức Anonymous
Phạm vi Anonymous
(cid:1) By using anonymous methods,
(cid:1) The scope of the parameters of an anonymous method
(cid:2) is the anonymous-method-block.
(cid:2) the coding overhead in instantiating delegates is reduced
(cid:2) because it does not need to create a separate method.
(cid:1) It is an error
(cid:2) to have a jump statement, such as goto, break, or continue, inside the
(cid:1) Creating anonymous methods is essentially a way
anonymous method block if the target is outside the block.
(cid:2) to pass a code block as a delegate parameter.
(cid:1) It is also an error
// Create a delegate.
delegate void Del(int x);
// Instantiate the delegate using an anonymous method.
Del d = delegate(int k) { /* ... */ };
(cid:2) to have a jump statement, such as goto, break, or continue, outside the
anonymous method block if the target is inside the block.
// Create a handler for a click event.
button1.Click += delegate(System.Object o, System.EventArgs e) {
System.Windows.Forms.MessageBox.Show("Click!");
};
System.Threading.Thread t1 = new System.Threading.Thread(delegate() {
System.Console.Write("Hello, ");
System.Console.WriteLine("World!");
});
.NET Programming - Nguyễn Đạt Thông 195 .NET Programming - Nguyễn Đạt Thông 196
49
2/19/2014
Biến Outer
Đặc điểm của biến Outer
(cid:1) The local variables and parameters
(cid:1) The lifetime of a captured variable
(cid:2) whose scope contains an anonymous method declaration are
(cid:2) extends until the delegates that reference the anonymous methods are eligible
called outer variables of the anonymous method.
for garbage collection.
(cid:1) An anonymous method cannot access the ref or out parameters of
(cid:1) A reference to the outer variable
an outer scope.
(cid:2) is said to be captured when the delegate is created.
void TestAnonymous(ref int N) {
(cid:1) Anonymous methods are not allowed on the left side of the is
int n = 0;
Del d = delegate(int nn) {
System.Console.WriteLine("Copy #:{0}", ++n);
operator.
// Cannot use ref or out parameter 'N' inside an
// anonymous method, lambda expression, or query expression
System.Console.WriteLine("Copy #:{0}", ++N);
};
}
.NET Programming - Nguyễn Đạt Thông 197 .NET Programming - Nguyễn Đạt Thông 198
Lambda
Biểu thức Lambdas
(cid:1) A lambda expression is an anonymous function
(cid:1) A lambda expression with an expression on the right side
(cid:2) that can used to create delegates or expression tree types.
(cid:2) is called an expression lambda.
(input parameters) => expression
(cid:1) By using lambda expressions, local functions can be
(cid:1) The parentheses are optional only if the lambda has one input
(cid:2) passed as arguments or
(cid:2) returned as the value of function calls.
parameter; otherwise they are required.
delegate int del(int i);
static void TestLambda() {
del myDelegate = x => x * x;
int j = myDelegate(5); // j = 25
(x, y) => x == y
}
(int x, string s) => s.Length > x
○ The delegate signature has one implicitly-typed input parameter of type int, and
returns an int.
() => SomeMethod()
○ The lambda expression also has one input parameter and a return value
x => x > 0
.NET Programming - Nguyễn Đạt Thông 199 .NET Programming - Nguyễn Đạt Thông 200
50
2/19/2014
Phát biểu Lambda
Kiểu dữ liệu Nested
(cid:1) A statement lambda resembles an expression lambda
(cid:1) A type defined within a class or structure is called a nested type.
(cid:2) except that the statement(s) is enclosed in braces.
(cid:1) Nested types default to private,
(input parameters) => { statements; }
(cid:2) but can be made public, protected internal, protected, internal, or
private.
(cid:1) The body of a statement lambda can consist of any number of
(cid:1) The nested, or inner type can access the containing, or outer type.
statements;
(cid:2) however, in practice there are typically no more than two or three.
(cid:2) Nested types can access private and protected members of the containing
type, including any inherited members.
delegate void TestDelegate(string s);
// ...
TestDelegate myDel = n => {
string s = n + " " + "World";
Console.WriteLine(s);
};
myDel("Hello");
.NET Programming - Nguyễn Đạt Thông 201 .NET Programming - Nguyễn Đạt Thông 202
Kiểu dữ liệu Nested: Ví dụ
Ghi chú
(cid:1) Example
public class Container
{
private int priv;
public class Nested
{
private int my_priv;
public Nested() { }
public Nested(Container parent)
{
my_priv = parent.priv;
}
}
}
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
.NET Programming - Nguyễn Đạt Thông 203 .NET Programming - Nguyễn Đạt Thông 204
51
2/19/2014
Kế thừa – Inheritance
Kế thừa trong C#
(cid:1) Declare and use a new class as a descendant of another class
(cid:1) The class from which the other classes can inherit is called base
class.
(cid:1) Saves trouble of re-writing code
(cid:1) Two types of Inheritance:
(cid:1) Provides luxury of code re-use
(cid:2) Single Inheritance
(cid:2) Multiple Inheritance
(cid:1) A class can inherit from only one class, but can implement many
interfaces.
(cid:2) At that time, in the list of base types, the class must go first.
.NET Programming - Nguyễn Đạt Thông 205 .NET Programming - Nguyễn Đạt Thông 206
Single Inheritance
Multiple inheritance
using System;
namespace Sample {
class Shape {
interface IConstructionVehicle
{
void ExecuteDump();
void TurnOnBackUpSound();
public int length;
public int breadth;
public void calculateArea(int len, int breadth)
{
}
}
interface Ivehicle
{
}
}
void Accelerate();
void Stop();
void TurnOnBackUpSound();
}
class Rectangle : Shape {
public Rectangle()
{
public class DumpTruck : IVehicle, IConstructionVehicle
{
length=0;
breadth=0;
void IConstructionVehicle.TurnOnBackUpSound()
{
Console.WriteLine("IConstructionVehicle TurnOnBackUpSound");
}
public void calculateRectArea(int len, int breadth)
{
Console.WriteLine ("Area of a Rectangle is {0}", len * breadth);
}
void IVehicle.TurnOnBackUpSound()
{
}
Console.WriteLine("IVehicle TurnOnBackUpSound");
}
}
}
.NET Programming - Nguyễn Đạt Thông 207 .NET Programming - Nguyễn Đạt Thông 208
52
2/19/2014
Đóng seal một lớp
Đa hình Polymorphism
(cid:1) A class is sealed
(cid:1) Polymorphism
(cid:2) when no class should be allowed to inherit from that class.
(cid:2) decision as to which method to call is made at runtime.
(cid:1) Keyword sealed is used to seal a class.
(cid:1) Polymorphism means
(cid:2) the “right” method gets called,
(cid:2) the one belonging to the actual object that is being referenced.
(cid:1) Example
(cid:1) Code is easier to understand.
// ...
sealed class ClassOne {
// Class Implementation
}
// ...
(cid:1) Helps the programmer to remember available functionality.
.NET Programming - Nguyễn Đạt Thông 209 .NET Programming - Nguyễn Đạt Thông 210
Từ khóa virtual
Đa hình trong C#
(cid:1) C# enables polymorphism through inheritance.
(cid:1) Keyword virtual is used in the definition of a method to support
polymorphism.
(cid:1) Through inheritance, a class can be used as more than one type
(cid:1) Used to modify method declaration in a class
(cid:2) it can be used as its own type,
(cid:2) any base types,
(cid:2) or any interface type if it implements interfaces.
(cid:1) Child classes are free to implement their own versions of virtual
method using override keyword.
(cid:1) Polymorphism keywords
(cid:1) virtual modifier cannot be used
(cid:2) with modifiers like static and override
(cid:2) virtual
(cid:2) override
(cid:2) sealed
(cid:2) new
.NET Programming - Nguyễn Đạt Thông 211 .NET Programming - Nguyễn Đạt Thông 212
53
2/19/2014
Từ khóa override
Đa hình: Ví dụ
class Class1 {
(cid:1) Used to modify a method
public virtual void Hello() {
System.Console.Write("Hello from Class1");
}
}
(cid:1) An override method provides a new implementation of the base
class Class2 : Class1 {
public override void Hello() {
method.
(cid:2) The base method should be declared as virtual (or abstract)
base.Hello();
System.Console.Write(" and hello from Class2 too");
}
public static void Main1(string[] args) {
(cid:1) Accessibility level of a base method cannot be changed by a method
overriding it.
Class2 c2 = new Class2();
c2.Hello();
System.Console.WriteLine();
Class1 c1 = new Class2();
c1.Hello();
System.Console.ReadLine();
}
(cid:1) Keywords new, static, virtual cannot be used along with
}
override modifier
.NET Programming - Nguyễn Đạt Thông 213 .NET Programming - Nguyễn Đạt Thông 214
Từ khóa sealed
Từ khóa new
(cid:1) Virtual members remain virtual indefinitely
(cid:1) Used as a modifier.
(cid:2) No matter how many classes have been declared between the class that
originally declared the virtual member.
(cid:1) new modifier is used to explicitly
(cid:2) hide a member that is inherited from the base class.
(cid:1) A derived class can stop virtual inheritance by declaring an override
as sealed.
(cid:1) sealed methods can be replaced by derived classes
(cid:2) using the new keyword.
(cid:1) It is an error
(cid:2) to use both new and override on the same method.
.NET Programming - Nguyễn Đạt Thông 215 .NET Programming - Nguyễn Đạt Thông 216
54
2/19/2014
Đa hình: Ví dụ
Ghi chú
public class Base {
public static int val = 123;
}
public class Derv : Base {
public static int val = 456;
// WARNING: new modifier required to hide "val" from base class
}
class IntAddition {
public virtual void add() { // "add" is virtual
Console.WriteLine("The Sum of the two numbers");
}
}
class FloatAddition : IntAddition {
public sealed override void add() { // prevent derived class to override
Console.WriteLine("The Sum of the two float numbers");
}
}
class StringAddition : FloatAddition {
public new void add() { // hide "add" from base class
Console.WriteLine("The Sum of the two strings");
}
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
}
.NET Programming - Nguyễn Đạt Thông 217 .NET Programming - Nguyễn Đạt Thông 218
Lớp trừu tượng và Interfaces
Lớp trừu tượng
(cid:1) Abstract base classes
(cid:1) The abstract classes are classes solely for the purpose of inheritance
(cid:2) cannot be instantiated nor can they be sealed.
(cid:2) to define features of derived, non-abstract classes.
(cid:1) The purpose of an abstract class is to provide a common definition of
(cid:1) Abstract class definitions are not complete
(cid:2) derived classes must define the missing pieces.
a base class
(cid:2) that multiple derived classes can share.
(cid:1) An interface contains definitions for a group of related functionalities
(cid:1) C# allows creation of Abstract Base classes
(cid:2) that a class or a structure can implement.
(cid:2) by an addition of the abstract modifier to the class definition.
.NET Programming - Nguyễn Đạt Thông 219 .NET Programming - Nguyễn Đạt Thông 220
55
2/19/2014
Đặc tính của lớp trừu tượng
Sử dụng lớp trừu tượng
(cid:1) Abstract classes may also define abstract methods.
(cid:1) If a virtual method is declared abstract,
(cid:2) it is still virtual to any class inheriting from the abstract class.
(cid:1) Abstract methods have no implementation
(cid:2) and its actual implementation is written in the derived class.
(cid:1) A class inheriting an abstract method
(cid:2) cannot access the original implementation of the method.
public class D {
(cid:1) Derived classes of the abstract class must implement all abstract
public virtual void DoWork(int i) {
// Original implementation.
methods.
}
}
public abstract class E : D {
(cid:1) Abstract methods can override virtual methods.
public abstract override void DoWork(int i);
// change virtual to abstract
}
public class F : E {
public override void DoWork(int i) {
// New implementation.
// cannot access DoWork of class D
}
}
.NET Programming - Nguyễn Đạt Thông 221 .NET Programming - Nguyễn Đạt Thông 222
Interfaces
Kế thừa Interface
(cid:1) An interface is a pure abstract base class.
(cid:1) New Interfaces can be created
(cid:2) by combining together other interfaces.
(cid:1) It can contain only abstract methods and no method implementation.
(cid:1) The syntax for this is similar to that used for inheritance,
(cid:2) except that more than one interface can be merged to form a single interface.
(cid:1) A class that implements a particular interface
(cid:2) must implement the members listed by that interface.
interface IAllFile : IFile, IFileTwo {
// More operations can be added if necessary
//(apart from that of IFile & IFileTwo)
public interface IFile {
}
// method declaration of interface
int delFile();
void disFile();
}
.NET Programming - Nguyễn Đạt Thông 223 .NET Programming - Nguyễn Đạt Thông 224
56
2/19/2014
Các thành phần của Interface
Trừu tượng hóa Interface
// interface
public interface ICompare {
(cid:1) Interface members are automatically public,
(cid:2) and they can't include any access modifiers.
int GetValue();
int Compare(ICompare ic);
}
// abstract
abstract public class BaseClass : ICompare {
(cid:1) An interface can specify
int nValue;
public BaseClass(int nInitialValue) {
nValue = nInitialValue;
public interface ISampleInterface {
}
public int Value {
get { return GetValue(); }
// interface property
type name {
get; set;
}
}
public int GetValue() {
return nValue;
(cid:2) a property
(cid:2) an indexer
(cid:2) an event
(cid:2) a method
}
public abstract int Compare(ICompare bc);
// interface indexer
element_type this[int index] {
get; set;
}
}
// implement interface and abstract class
public class SubClass : BaseClass {
public SubClass(int nInitialValue) : base(nInitialValue) { }
public override int Compare(ICompare ic) {
// interface event
event delegate_type event_name;
return GetValue().CompareTo(ic.GetValue());
}
}
}
.NET Programming - Nguyễn Đạt Thông 225 .NET Programming - Nguyễn Đạt Thông 226
Hiện thực hóa Interface
Hiện thực ngầm định – implicit
(cid:1) A class can implement two interfaces
interface IControl {
void Paint();
(cid:2) that contain a member with the same signature.
}
interface ISurface {
void Paint();
}
public class SampleClass : IControl, ISurface {
(cid:1) If the class implement that member,
// Both ISuface.Paint() and IControl.Paint call this method
public void Paint() {
(cid:2) both interfaces to use that member as their implementation.
System.Console.WriteLine("Paint method in SamppleClass");
}
}
class Test {
(cid:1) If the two interface members do not perform the same function,
static void Main() {
(cid:2) however, this can lead to an incorrect implementation of one or both of the
SampleClass sc = new SampleClass();
IControl ctrl = (IControl)sc;
ISurface srfc = (ISurface)sc;
interfaces.
// The following lines all call the same method.
sc.Paint(); // Output: Paint method in SamppleClass
ctrl.Paint(); // Output: Paint method in SamppleClass
srfc.Paint(); // Output: Paint method in SamppleClass
}
}
.NET Programming - Nguyễn Đạt Thông 227 .NET Programming - Nguyễn Đạt Thông 228
57
2/19/2014
Hiện thực tường minh – explicit
Hiện thực tường minh
interface IControl {
void Paint();
(cid:1) An explicitly implemented member cannot be accessed through a
}
interface ISurface {
void Paint();
class instance,
(cid:2) but only through an instance of the interface.
}
public class SampleClass : IControl, ISurface {
void IControl.Paint() {
System.Console.WriteLine("IControl.Paint");
(cid:1) If an interface member is not implemented explicitly,
}
void ISurface.Paint() {
System.Console.WriteLine("ISurface.Paint");
(cid:2) the instance implementation is used.
}
}
class Test {
static void Main() {
SampleClass sc = new SampleClass();
IControl ctrl = (IControl)sc;
ISurface srfc = (ISurface)sc;
sc.Paint(); // ERROR: Compiler error.
ctrl.Paint(); // Calls IControl.Paint on SampleClass.
srfc.Paint(); // Calls ISurface.Paint on SampleClass.
}
}
.NET Programming - Nguyễn Đạt Thông 229 .NET Programming - Nguyễn Đạt Thông 230
Namespaces
Khai báo namespace
(cid:1) Used to avoid naming conflicts.
class SonyTVLCD { }
class SonyTVCRT { }
class SonyTVFlatron { }
class SonyTVPlasma : SonyTVFlatron { }
(cid:1) Elements designed to help us organize our code.
class SamsungLCD { }
class SamsungTVCRT { }
class SamsungTVFlatron : SamsungLCD { }
class SamsungTVPlasma { }
(cid:1) Reduces complexity when code is to be re-used for some other
application.
namespace Sony.Televison {
public class LCD { }
public class CRT { }
public class Flatron { }
public class Plasma : Flatron { } // "Flatron" is unqualified class name
(cid:1) Namespace System contains all the code required to interact with
}
namespace Samsung {
the system.
public class LCD { }
namespace Televison { // nested namespace
(cid:1) Nested namespaces are child namespaces of other namespaces.
public class CRT { }
public class Flatron : LCD { } // "LCD" is unqualified class name
public class Plasma : Flatron { } // "Flatron" is unqualified class name
}
}
.NET Programming - Nguyễn Đạt Thông 231 .NET Programming - Nguyễn Đạt Thông 232
58
2/19/2014
Truy xuất Namespace
“Tên đầy đủ”
(cid:1) Namespaces are implicitly public.
(cid:1) To use a class inside its namespace, we need to specify the class
name only.
(cid:2) This is known as unqualified naming.
(cid:1) Namespaces cannot be protected, private or internal.
namespace Sony.Televison {
(cid:1) To use a class outside a namespace it has to be referred by using its
fully qualified name as
public class LCD { }
public class CRT { }
public class Flatron { }
public class Plasma : Flatron { } // "Flatron" is unqualified class name
namespace.nested_namespace.class_name
}
namespace Samsung {
public class LCD { }
public namespace Televison { // ERROR: namespace cannot have modifiers
(cid:1) Example
public class CRT { }
public class Flatron : LCD { } // "LCD" is unqualified class name
public class Plasma : Flatron { } // "Flatron" is unqualified class name
}
}
System.Console
System.Net.Security.SslStream
System.Windows.Forms.Button
.NET Programming - Nguyễn Đạt Thông 233 .NET Programming - Nguyễn Đạt Thông 234
Từ khóa using
Sử dụng “alias”
(cid:1) With qualified naming
(cid:2) the code gets longer and confusing.
(cid:1) using alias directives provides us with the facility
(cid:2) to pull just one class from the namespace into the scope.
(cid:1) With “using namespaces” statement,
(cid:1) Syntax
(cid:2) long confusing names can be made short and meaningful.
using cls_alias = qualified_path_to_class;
using ns_alias = qualified_path_to_namespace;
(cid:1) The using namespace directives can have global scope
(cid:2) provided they are declared before any member declarations.
.NET Programming - Nguyễn Đạt Thông 235 .NET Programming - Nguyễn Đạt Thông 236
59
2/19/2014
using: Ví dụ
Các Namespace thông dụng
using Samsung.Televison;
using Sony.Televison;
Namespace/Class
Description
namespace TestQualified {
public class TestTV {
public void ChooseTV() {
System
Much of the functionality of the BCL is contained within
this namespace. It comprises of various other
namespaces within it.
// use qualified class names
Samsung.Televison.Flatron tv1 = new Samsung.Televison.Flatron();
Sony.Televison.Plasma tv2 = new Sony.Televison.Plasma();
}
System.Array class
}
Contains methods for manipulating arrays.
}
System.Threading
Contains classes for Multi-Threading.
namespace TestUnqualified {
System.Math class
Contains methods for performing mathematical functions.
// alias Flatron here: TestUnqualified.CRT ~~ Samsung.Televison.CRT
using CRT = Samsung.Televison.CRT;
public class TestTV {
System.IO
public void ChooseTV() {
Contains classes for reading and writing to files and
streams.
System.Reflection
Contains classes for reading metadata from assemblies.
// use unqualified class names through "using namespace"
LCD tv1 = new LCD(); // LCD of "Sony.Televison" namespace
CRT tv4 = new CRT(); // CRT of "TestUnqualified" ~ Samsung.Televison.CRT
Flatron tv3 = new Flatron(); // Flatron of which namespace ????
}
System.Net
}
Contains classes for Internet access and socket
programming
}
.NET Programming - Nguyễn Đạt Thông 237 .NET Programming - Nguyễn Đạt Thông 238
Tóm lược
Tóm lược
(cid:1) How to declare a class with members?
(cid:1) How to make class properties and indexers?
(cid:1) How to protect class members?
(cid:1) What is delegates and events?
(cid:1) How to write class methods?
(cid:1) How to subscribe and unsubscribe to events?
(cid:1) How to overload class methods?
(cid:1) How to use anonymous methods and lambdas?
(cid:1) How to overload operators for a class?
(cid:1) How to use interfaces and abstract classes?
(cid:1) How to use namespaces to organize classes?
.NET Programming - Nguyễn Đạt Thông 239 .NET Programming - Nguyễn Đạt Thông 240
60
2/19/2014
Tham khảo thêm
Tham khảo thêm
(cid:1) Tutorial: Delegates
(cid:1) Tutorial: Properties
http://msdn.microsoft.com/en-us/library/aa288470(v=vs.71).aspx
http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx
(cid:1) Tutorial: Events
(cid:1) Tutorial: Indexers
http://msdn.microsoft.com/en-us/library/aa288465(v=vs.71).aspx
http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx
(cid:1) Asynchronous Programming with Async and Await
(cid:1) Tutorial: Indexed Properties
http://msdn.microsoft.com/en-us/library/hh191443.aspx
http://msdn.microsoft.com/en-us/library/aa288464(v=vs.71).aspx
(cid:1) Tutorial: Operator overloading
http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx
.NET Programming - Nguyễn Đạt Thông 241 .NET Programming - Nguyễn Đạt Thông 242
Tham khảo thêm
Tham khảo thêm
(cid:1) Tutorial: Methods
(cid:1) Members
http://www.csharp-station.com/Tutorial/CSharp/Lesson05
http://msdn.microsoft.com/en-us/library/ms173113.aspx
(cid:1) Tutorial: Properties
(cid:1) Methods
http://www.csharp-station.com/Tutorial/CSharp/Lesson10
http://msdn.microsoft.com/en-us/library/ms173114.aspx
(cid:1) Tutorial: Indexers
(cid:1) Covariance and Contravariance
http://www.csharp-station.com/Tutorial/CSharp/Lesson11
http://msdn.microsoft.com/en-us/library/ee207183.aspx
(cid:1) Tutorial: Overloading Operators
(cid:1) Events
http://www.csharp-station.com/Tutorial/CSharp/Lesson18
http://msdn.microsoft.com/en-us/library/awbftdfh(v=vs.80).aspx
.NET Programming - Nguyễn Đạt Thông 243 .NET Programming - Nguyễn Đạt Thông 244
61
2/19/2014
Tham khảo thêm
Ghi chú
(cid:1) Overloadable operators
http://msdn.microsoft.com/en-us/library/8edha89s.aspx
(cid:1) Anonymous Functions
http://msdn.microsoft.com/en-us/library/bb882516.aspx
(cid:1) Interfaces
http://msdn.microsoft.com/en-us/library/vstudio/ms173156.aspx
(cid:1) Explicit Interface Implementation
http://msdn.microsoft.com/en-us/library/ms173157.aspx
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
.NET Programming - Nguyễn Đạt Thông 245 .NET Programming - Nguyễn Đạt Thông 246
Window Forms
(cid:1) Graphic User Interface
(cid:1) Windows Forms
(cid:1) Event-Handling Model
Chương 3
(cid:1) Common controls
(cid:1) Containers
(cid:1) Menu and Toolbars
(cid:1) Custom Controls
.NET Programming - Nguyễn Đạt Thông 247 .NET Programming - Nguyễn Đạt Thông 248
62
2/19/2014
Giao diện đồ họa
Các thành phần giao diện cơ bản
(cid:1) Label
(cid:1) Graphical User Interface (GUI)
(cid:2) Used to display text or images that cannot be edited by the user.
(cid:2) Allows interaction with program visually
(cid:2) Is an set of visual objects (components), accessed via keyboard or mouse.
(cid:1) TextBox
(cid:2) An area in which the user inputs data from the keyboard. The area also can
display information.
(cid:1) Types of GUI applications
(cid:2) Windows Forms applications
(cid:2) Web applications
(cid:1) Button
(cid:2) allows the user to click it to perform an action.
.NET Programming - Nguyễn Đạt Thông 249 .NET Programming - Nguyễn Đạt Thông 250
Các thành phần giao diện cơ bản
Windows Forms
(cid:1) CheckBox
(cid:1) Window Form applications are GUI applications
(cid:2) A GUI control that is either selected or not selected.
(cid:2) run on Microsoft Windows operating systems.
(cid:1) ComboBox
(cid:1) .NET framework provides classes
(cid:2) A drop-down list of items from which the user can make a selection, by clicking
(cid:2) to build up Window Form applications rapidly.
an item in the list or by typing into the box, if permitted.
(cid:1) Assembly: System.Windows.Forms.dll
(cid:1) Panel
(cid:2) A container in which components can be placed.
(cid:1) Namespace: System.Windows.Forms
.NET Programming - Nguyễn Đạt Thông 251 .NET Programming - Nguyễn Đạt Thông 252
63
2/19/2014
Cửa sổ Form
Các Controls và Events
(cid:1) Customized forms contain standard and custom controls to build up
(cid:1) Control
the user interface.
(cid:2) Component with graphical part, such as button or label
(cid:2) Are visible
(cid:1) Event
(cid:2) Generated by movement from mouse or keyboard
(cid:2) Event handlers performs action
(cid:2) Specifics written by programmer
.NET Programming - Nguyễn Đạt Thông 253 .NET Programming - Nguyễn Đạt Thông 254
Các thành phần Windows Forms
Tạo một cửa sổ Form
(cid:1) To add new form, select “Windows Form” from menu “Add”
.NET Programming - Nguyễn Đạt Thông 255 .NET Programming - Nguyễn Đạt Thông 256
64
2/19/2014
Lớp Form
Thiết kế giao diện cửa sổ Form
(cid:1) Visual Studio creates a designer to help user to design the form.
(cid:1) Visual Studio automatically creates a new class inherited from
System.Windows.Forms.Form class.
.NET Programming - Nguyễn Đạt Thông 257 .NET Programming - Nguyễn Đạt Thông 258
Tùy chỉnh cửa sổ Form
Các thuộc tính của cửa sổ Form
Property
Description
(cid:1) To help user to customize the form (change its properties), Visual
Studio provides “Properties” window.
BackColor/ForeColor Color of background and text
BackGroundImage
Background image of the form
AcceptButton
The button which will fire “click” event
whenever user press “enter”
CancelButton
The button which will fire “click” event
whenever user press “escape”
Controls
The collection of child controls. It allows to
add/remove controls programmatically
FormBorderStyle
Border style of the form
Opacity
How transparent the form is.
.NET Programming - Nguyễn Đạt Thông 259 .NET Programming - Nguyễn Đạt Thông 260
65
2/19/2014
Các thuộc tính của cửa sổ Form
Các thao tác trên cửa sổ Form
Method
Description
Property
Description
AutoSize
Allow form to automatically calculate its size
Show()
Show the form and allow users to focus
to parent forms
CauseValidation
Allow child controls to fire “Validate” event which
used to validate data input.
ShowDialog()
TopMost
Allow the form to be put over all other forms
Show the form and users can only
focus to parent forms once the form is
closed.
Return type: DialogResult.
WindowState
Close()
{Normal, Minimized, Maximized}. The
starting state of the form.
Close the form
Cursor
Style of the cursor when it enters the form.
this.DialogResult =
DialogResult.OK
Set dialog result to “OK” before closing
the form
Icon
Icon of the form
This.DialogResult =
DialogResult.Cancel
Set dialog result to “Cancel” before
closing the form
.NET Programming - Nguyễn Đạt Thông 261 .NET Programming - Nguyễn Đạt Thông 262
Các sự kiện trên cửa sổ Form
Mô hình xử lý sự kiện
Event
Description
(cid:1) GUIs are event driven.
Load
The event which is fired after the form has
been loaded successfully.
(cid:1) Event handlers
(cid:2) Methods that process events and perform tasks.
Paint
The event which is fired whenever the form
need to redrawn.
Closed
Occur when the form is closed
(cid:1) Associated delegates
Closing
Occur when the form is closing
(cid:2) Objects that reference methods
(cid:2) Contain lists of method references
Keyboard-related events
○ Must have same signature
KeyPress,
KeyDown,...
(cid:2) Intermediaries for objects and methods
(cid:2) Signature for control’s event handler
Mouse-related events
MouseHover,
MouseDown,
MouseLeave
.NET Programming - Nguyễn Đạt Thông 263 .NET Programming - Nguyễn Đạt Thông 264
66
2/19/2014
Mô hình xử lý sự kiện
Xử lý sự kiện
(cid:1) Event handler
(cid:2) Must have same signature as corresponding delegate
(cid:2) Must be registered with delegate object
○ Add event handlers to the delegate’s invocation list
(cid:2) New delegate object for each event handler
Handler 1 for event E
calls
calls
(cid:1) Event multicasting
Object A raises event E
Delegate for event E
Handler 2 for event E
(cid:2) Have multiple handlers for one event
(cid:2) Order called for event handlers is indeterminate
Handler 3 for event E
.NET Programming - Nguyễn Đạt Thông 265 .NET Programming - Nguyễn Đạt Thông 266
Đăng ký xử lý sự kiện
Đăng ký xử lý sự kiện
.NET Programming - Nguyễn Đạt Thông 267 .NET Programming - Nguyễn Đạt Thông 268
67
2/19/2014
Xử lý sự kiện chuột
Thông tin về sự kiện chuột
Event
Description
(cid:1) MouseEventArg: Provides data for the MouseUp, MouseDown, and
MouseMove events.
MouseEnter
Occurs when the mouse cursor enters the area
of the control.
(cid:2) Button: Mouse button that was pressed (left, right, middle or none).
MouseLeave
Occurs when the mouse cursor leaves the area
of the control.
(cid:2) Clicks: The number of times the mouse button was clicked.
MouseDown
Occurs when the mouse button is pressed while
its cursor is over the area of the control.
(cid:2) X: The x - coordinate of the event, relative to the component.
MouseHover
Occurs when the mouse cursor hovers over the
area of the control.
(cid:2) Y: The y - coordinate of the event, relative to the component.
MouseMove
Occurs when the mouse cursor is moved while
in the area of the control.
MouseUp
Occurs when the mouse button is released
when the cursor is over the area of the control.
.NET Programming - Nguyễn Đạt Thông 269 .NET Programming - Nguyễn Đạt Thông 270
Xử lý sự kiện bàn phím
Thông tin về sự kiện bàn phím
(cid:1) KeyEventArgs: Provides data for the KeyDown and KeyUp events.
Event
Description
(cid:2) Shift: Indicates whether the Shift key was pressed.
KeyDown
Occurs when key is initially pushed down.
KeyUp
Occurs when key is released.
(cid:2) Handled: Whether the event was handled.
KeyPress
Occurs when the control has focus and the user
presses and releases a key.
(cid:2) KeyCode: Returns the key code for the key, as a Keys enumeration.
(cid:1) KeyEventArg provides data for the KeyDown and KeyUp events.
(cid:2) KeyData: Returns the key code as a Keys enumeration, combined with
modifier information.
(cid:1) KeyPressEventArg provides data for the KeyPress event.
(cid:2) KeyValue: Returns the key code as an int, rather than as a Keys
enumeration.
.NET Programming - Nguyễn Đạt Thông 271 .NET Programming - Nguyễn Đạt Thông 272
68
2/19/2014
Thông tin về sự kiện bàn phím
Ghi chú
(cid:1) KeyPressEventArg provides data for the KeyPress event.
(cid:2) KeyChar: Returns the ASCII character for the key pressed.
(cid:2) Alt: Indicates whether the Alt key was pressed.
(cid:2) Control: Indicates whether the Control key was pressed.
(cid:2) Handled: Whether or not the KeyPress event was handled.
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
.NET Programming - Nguyễn Đạt Thông 273 .NET Programming - Nguyễn Đạt Thông 274
Các thành phần giao diện phổ biến
Các thuộc tính chung
(cid:1) .NET framework provides many common controls
Property
Description
BackColor
Background color of the control.
BackgroundImage
Background image of the control.
Enabled
Whether the control is enabled (i.e., if the user
can interact with it). A disabled control will still be
displayed, but “grayed-out”—portions of the
control will become gray.
Focused
Whether a control has focus.
Font
Font used to display control’s Text.
ForeColor
Foreground color of the control. This is usually
the color used to display the control’s Text
property.
(cid:2) Label
(cid:2) TextBox
(cid:2) Button
(cid:2) CheckBox
(cid:2) CheckedListBox
(cid:2) RadioButton
(cid:2) ListBox
(cid:2) ListView
(cid:2) TreeView
(cid:2) DateTimePicker
(cid:2) …
TabIndex
Tab order of the control..
.NET Programming - Nguyễn Đạt Thông 275 .NET Programming - Nguyễn Đạt Thông 276
69
2/19/2014
Các thuộc tính chung
Các thao tác chung
Property
Method
Description
TabStop
Focus()
Transfers the focus to the control.
Description
If true, user can use the Tab key to select the
control.
Hide()
Hides the control (sets Visible to false).
Text
Text associated with the control. The location
and appearance varies with the type of control.
Show()
Shows the control (sets Visible to true).
TextAlign
The alignment of the text on the control.
BringToFront()
Brings the control to the front of the z-order.
Visible
Whether the control is visible or hidden.
GetChildAtPoint()
Retrieves the child control that is located at the
specified coordinates.
Anchor
Side of parent container at which to anchor
control—values can be combined, such as Top,
Left.
Invoke()
Dock
Side of parent container to dock control—values
cannot be combined.
Executes the specified delegate on the thread
that owns the control's underlying window
handle.
Size
Scale()
Scales the control and any child controls.
Size of the control. Takes a Size structure,
which has properties Height and Width.
.NET Programming - Nguyễn Đạt Thông 277 .NET Programming - Nguyễn Đạt Thông 278
Ví dụ
Labels
(cid:1) Manipulating the Anchor property of control.
(cid:1) Used to display text or images that cannot be edited by the user.
(cid:1) Common Properties
(cid:2) Fonts: The font used by the text on the Label
(cid:2) Text: The text to appear on the Label.
(cid:2) TextAlign: The alignment of the Label’s text on the control.
Control expands along top
portion of the form
.NET Programming - Nguyễn Đạt Thông 279 .NET Programming - Nguyễn Đạt Thông 280
70
2/19/2014
Text Boxes
Thuộc tính của Text Box
(cid:1) An area in which the user inputs data from the keyboard.
Property
Description
(cid:2) The area also can display information.
Text
The text of the textbox
TextLength
The length of text in the textbox. (read-only)
(cid:1) Masked Tex tBox: Used to prompt for text input following a mask.
TextAlign
How text is aligned in textbox
Multiline
The value indicating whether this is a multiline
textbox
PasswordChar
The char used to mask chars of a password.
SelectedText
The value indicates the current selected text
SelectionStart The starting point of text selected in the textbox
ReadOnly
The value indicating whether text in the text box
is read-only
.NET Programming - Nguyễn Đạt Thông 281 .NET Programming - Nguyễn Đạt Thông 282
Thuộc tính Mask
Các sự kiện trên Text Box
(cid:1) Mask
Event
Description
(cid:2) get or set the mask of the masked textbox.
TextChanged
Occurs when the Text property value changes
(cid:1) Use predefined masks
Occurs when the control is validating (lost focus).
Parameters:
Validating
object sender,
CancelEventArgs e
KeyPress
Occurs when a key is pressed while the control has
focus.
Parameters:
object sender,
KeyPressEventArgs e
.NET Programming - Nguyễn Đạt Thông 283 .NET Programming - Nguyễn Đạt Thông 284
71
2/19/2014
Hiệu chỉnh Mask
Buttons
(cid:1) Button control allows the user to click it to perform an action.
(cid:2) The Button control can display both text and images.
Masking element Description
(cid:1) Common Property
0
Digit, required. This element will accept any single digit between 0
and 9.
(cid:2) Text: Text displayed on the Button face.
9
Digit or space, optional.
#
Digit or space, optional. Plus (+) and minus (-) signs are allowed.
(cid:1) Common Events
(cid:2) Click: Occurs when the user clicks the control. Default event when this control
L
Letter, required ([a..z] or [A..Z])
is double clicked in the designer.
?
Letter, optional ([a..z] or [A..Z])
,
Thousands placeholder (1,234)
.
Decimal placeholder (0.32)
.NET Programming - Nguyễn Đạt Thông 285 .NET Programming - Nguyễn Đạt Thông 286
Check Boxes
Check Boxes
(cid:1) A control that is either selected or not selected
(cid:1) Common Properties
(cid:2) Checked: Whether or not the CheckBox has been checked.
(cid:2) Text: Text displayed to the right of the CheckBox (called the label).
(cid:2) True or false state
(cid:2) No restriction on usage
(cid:1) Common Events
(cid:2) CheckedChanged: Occurs whenever the Check property is changed. Default
event when this control is double clicked in the designer.
(cid:2) CheckStateChanged: Occurs whenever the CheckState property is
Result when bold is selected
changed.
.NET Programming - Nguyễn Đạt Thông 287 .NET Programming - Nguyễn Đạt Thông 288
72
2/19/2014
Radio Buttons
Radio Buttons
(cid:1) Common Properties
(cid:1) RadioButton
(cid:2) Checked: Whether the RadioButton is checked.
(cid:2) Text: Text displayed to the right of the RadioButton (called the label).
(cid:2) Grouped together
(cid:2) Only one can be true
(cid:2) Mutually exclusive options
(cid:1) Common Events
(cid:2) Click: Occurs when the control is clicked.
(cid:2) CheckedChanged
○ Occurs whenever the Check property changes value.
○ Default event when this control is double clicked in the designer.
.NET Programming - Nguyễn Đạt Thông 289 .NET Programming - Nguyễn Đạt Thông 290
Picture Boxes
Picture Boxes
(cid:1) Used to display graphics
(cid:1) Common Properties
(cid:2) in bitmap, GIF, JPEG, metafile, or icon format.
(cid:2) Image: Image to display in the PictureBox.
(cid:2) SizeMode: Enumeration that controls image sizing and positioning.
○ Normal (default) puts image in top-left corner of PictureBox and CenterImage
puts image in middle.
○ StretchImage resizes image to fit in PictureBox.
○ AutoSize resizes PictureBox to hold image.
(cid:1) Common Events
(cid:2) Click:
○ Occurs when the user clicks the control.
○ Default event when this control is double clicked in the designer.
.NET Programming - Nguyễn Đạt Thông 291 .NET Programming - Nguyễn Đạt Thông 292
73
2/19/2014
List Boxes
List Boxes
(cid:1) Common Properties
(cid:1) Use to display a list from which the user can select items.
(cid:2) SelectionMode: Indicate if the list box is to be single-select, multi-select, or
not selectable.
(cid:2) Items: The items of the list box
(cid:2) MultiColumn: Indicate if values should be displayed in columns horizontally.
(cid:2) SelectedIndex: Gets or sets the zero-based index of the currently selected
item.
(cid:2) SelectedIndices: Returns a collection of the indices of all currently selected
items.
.NET Programming - Nguyễn Đạt Thông 293 .NET Programming - Nguyễn Đạt Thông 294
List Boxes
List Boxes
(cid:1) ListBox Common Methods
(cid:1) Common Properties
(cid:2) GetSelected: Takes an index, and returns True if the corresponding item is
(cid:2) SelectedItem: Returns the currently selected item.
selected.
(cid:2) SelectedItems: Returns a collection of the currently selected item(s).
(cid:2) SelectedValue: Returns the value of the member property specified by the
(cid:2) Add: Adds an Item to the list of Items
○ listBox1.Items.Add("One");
○ listtBox1.Items.Add("Two");
ValueMember property.
(cid:2) RemoveAt: Removes the Item at the specified index within the collection
○ listBox1.Items.RemoveAt(row);
(cid:2) Sorted: Indicates whether items appear in alphabetical order. True causes
alphabetization; default is False.
(cid:2) Clear: Clear to all Items collection
○ listBox1.Items.Clear();
.NET Programming - Nguyễn Đạt Thông 295 .NET Programming - Nguyễn Đạt Thông 296
74
2/19/2014
List Boxes
Checked List Boxes
(cid:1) Extends ListBox by placing a check box at the left of each item.
(cid:1) Common Events
(cid:2) SelectedIndexChanged: Occurs when the value of SelectedIndex
property changes.
(cid:1) Can select more than one object at one time
(cid:1) Can add to, remove from or clear list
(cid:1) Can select multiple items from the list
.NET Programming - Nguyễn Đạt Thông 297 .NET Programming - Nguyễn Đạt Thông 298
Checked List Boxes
Checked List Boxes
(cid:1) CheckedListBox Common Properties
(cid:1) CheckedListBox Common Methods
(cid:2) CheckedItems: The collection of items that are checked. Not the same as the
(cid:2) GetItemChecked: Takes an index and returns true if corresponding item
selected items, which are highlighted (but not necessarily checked).
checked.
(cid:2) CheckedIndices: Returns indices for the items that are checked.
(cid:1) CheckedListBox Common Events
(cid:2) ItemCheck: Occurs when an item is checked or unchecked.
(cid:2) SelectionMode: Can only have values One (allows multiple selection) or None
○ ItemCheckEventArgs Properties
(does not allow multiple selection).
(cid:2) CurrentValue: Whether current item is checked or unchecked. Values Checked,
Unchecked or Indeterminate.
(cid:2) Index: Index of item that changed.
(cid:2) NewValue: New state of item.
.NET Programming - Nguyễn Đạt Thông 299 .NET Programming - Nguyễn Đạt Thông 300
75
2/19/2014
Combo Boxes
Combo Boxes
(cid:1) Combine TextBox and drop-down list.
(cid:1) Common Properties
(cid:2) Items: Collection of items in the ComboBox control.
(cid:1) Common Properties
(cid:2) MaxDropDownItems: Maximum number of items to display in the drop-down
(cid:2) DropDownStyle: Determines the type of combo box.
list (between 1 and 100). If value is exceeded, a scroll bar appears.
○ Simple means that the text portion is editable and the list portion is always visible.
○ DropDown (the default) means that the text portion is editable but an arrow button
must be clicked to see the list portion.
(cid:2) SelectedIndex: Returns index of currently selected item. If there is no
○ DropDownList means that the text portion is not editable.
currently selected item, -1 is returned.
(cid:2) SelectedItem: Returns the currently selected item.
(cid:2) Sorted: If true, items appear in alphabetical order. Default false.
.NET Programming - Nguyễn Đạt Thông 301 .NET Programming - Nguyễn Đạt Thông 302
Combo Boxes
Date-Time Pickers
(cid:1) DateTimePicker
(cid:1) ComboBox Common Methods
(cid:2) enables the user to select a date and time, and to display that date and time in a
specified format.
(cid:2) Add: Adds an Item to the list of Items
○ comboBox1.Items.Add("One");
○ comboBox1.Items.Add("Two");
(cid:1) Common Properties
(cid:2) RemoveAt: Removes the Item at the specified index within the collection
(cid:2) CustomFormat: the format string used to format the date and/or time displayed
○ comboBox1.Items.RemoveAt(row);
in the control.
(cid:2) Value: The current date/time value for this control.
(cid:2) Clear: Clear to all Items collection
○ comboBox1.Items.Clear();
.NET Programming - Nguyễn Đạt Thông 303 .NET Programming - Nguyễn Đạt Thông 304
76
2/19/2014
List Views
List View: View Modes
(cid:1) Used to display a collection of items as a grid.
(cid:1) List View can display items in 5 modes:
(cid:2) Large Icon
(cid:2) Details
(cid:2) Small Icon
(cid:2) List
(cid:2) Tile
.NET Programming - Nguyễn Đạt Thông 305 .NET Programming - Nguyễn Đạt Thông 306
ListViewItem
List Views
(cid:1) Each item in ListView is a ListViewItem.
(cid:1) Common Properties
(cid:2) Columns: The columns shown in Details View
(cid:2) Items: The items in the List View
(cid:2) View: Select one of 5 different views that items can be shown in.
(cid:2) FullRowSelect: Indicates whether all SubItems are highlighted along with the
item when selected.
(cid:1) Properties of ListViewItem
(cid:2) Text: displayed text of the item
(cid:2) SubItems: sub-items of the ListViewItem, be shown in Details mode.
(cid:2) ImageIndex: index of the image of the item.
(cid:2) SelectedIndex: Gets or sets the zero-based index of the currently selected
item.
(cid:1) Common Events
(cid:2) SelectedIndexChanged: Occurs when the value of SelectedIndex
property changes.
.NET Programming - Nguyễn Đạt Thông 307 .NET Programming - Nguyễn Đạt Thông 308
77
2/19/2014
List View: Ví dụ
Tree Views
(cid:1) Displays nodes hierarchically
(cid:1) Parent nodes have children
(cid:1) The first parent node is called the root
(cid:1) Each node of TreeView is a TreeNode.
Root nodes
Child nodes
Click to collapse node,
hiding child nodes
.NET Programming - Nguyễn Đạt Thông 309 .NET Programming - Nguyễn Đạt Thông 310
Tree Views
Tree Views
(cid:1) Common Properties
(cid:1) Common Properties
(cid:2) CheckBoxes: Indicates whether checkboxes appear next to nodes. True
(cid:2) Nodes: Lists the collection of TreeNodes in the control. Contains methods
displays checkboxes. Default is False.
○ Add (adds a TreeNode object),
○ Clear (deletes the entire collection) and
○ Remove (deletes a specific node). Removing a parent node deletes all its children.
(cid:2) ImageList: Indicates the ImageList used to display icons by the nodes.
○ An ImageList is a collection that contains a number of Image objects.
(cid:2) SelectedNode: Currently selected node.
(cid:1) Common Events
(cid:2) AfterSelect: Generated after selected node changes. Default when double-
clicked in designer.
.NET Programming - Nguyễn Đạt Thông 311 .NET Programming - Nguyễn Đạt Thông 312
78
2/19/2014
Tree Nodes
Tree Nodes
(cid:1) Common Properties
(cid:1) Common Properties
(cid:2) Checked: Indicates whether the TreeNode is checked. (CheckBoxes property
(cid:2) LastNode: Specifies the last node in the Nodes collection (i.e., last child in
must be set to True in parent TreeView.)
tree).
(cid:2) FirstNode: Specifies the first node in the Nodes collection (i.e., first child in
(cid:2) NextNode: Next sibling node.
tree).
(cid:2) PrevNode: Indicates the previous sibling node.
(cid:2) FullPath: Indicates the path of the node, starting at the root of the tree.
(cid:2) SelectedImageIndex: Specifies the index of the image to use when the node
(cid:2) ImageIndex: Specifies the index of the image to be shown when the node is
is selected.
deselected.
(cid:2) Text: Specifies the text to display in the TreeView.
.NET Programming - Nguyễn Đạt Thông 313 .NET Programming - Nguyễn Đạt Thông 314
Tree Nodes
Tree View: Ví dụ
(cid:1) Common Methods
(cid:2) Collapse: Collapses a node.
(cid:2) Expand: Expands a node.
(cid:2) ExpandAll: Expands all the children of a node.
(cid:2) GetNodeCount: Returns the number of child nodes.
(cid:2) Remove: Remove current node from the tree view control.
.NET Programming - Nguyễn Đạt Thông 315 .NET Programming - Nguyễn Đạt Thông 316
79
2/19/2014
Ghi chú
Containers
(cid:1) Containers help to organize (layout) controls.
(cid:2) Panel
(cid:2) Group Box
(cid:2) Tab Control
(cid:2) Split Container
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
.NET Programming - Nguyễn Đạt Thông 317 .NET Programming - Nguyễn Đạt Thông 318
Panels
Panel: Ví dụ
(cid:1) Panels are used to group other controls. They can have scrollbars.
Panel
(cid:1) Common Properties
Controls
inside Panel
(cid:2) AutoScroll: Whether scrollbars appear when the Panel is too small to hold
its controls. Default is false.
(cid:2) BorderStyle: Border of the Panel. Default is None.
(cid:2) Controls: The controls that the Panel contains.
Panel’s
ScrollBar
.NET Programming - Nguyễn Đạt Thông 320 .NET Programming - Nguyễn Đạt Thông 319
80
2/19/2014
Group Boxes
Tab Controls
(cid:1) GroupBoxes are used to group other controls.
(cid:1) Tab Controls are used to group controls into pages.
(cid:1) The GroupBox control is similar to the Panel control;
(cid:1) Each page of TabControl is another container, TabPage.
(cid:2) however, only the GroupBox control displays a caption, and only the Panel
control can have scroll bars.
(cid:1) Common Properties
TabPage
TabControl
(cid:2) Controls: The controls that the GroupBox contains.
(cid:2) Text: Text displayed on the top portion of the GroupBox (its caption).
Controls in
TabPage
.NET Programming - Nguyễn Đạt Thông 321 .NET Programming - Nguyễn Đạt Thông 322
Tab Controls
Split Containers
(cid:1) Common Properties
(cid:1) Split Containers are used to groups controls to 2 splitted resizable
panels.
(cid:1) Each panel of the SplitContainer is also a Panel.
(cid:2) SelectedIndex: Indicates index of TabPage that is currently selected.
(cid:2) SelectedTab: Indicates the TabPage that is currently selected.
(cid:2) TabCount: Returns the number of tabs.
(cid:2) TabPages: Gets the collection of TabPages within our TabControl.
(cid:1) Common Event
(cid:2) SelectedIndexChanged: Occurs when another TabPage is selected.
.NET Programming - Nguyễn Đạt Thông 323 .NET Programming - Nguyễn Đạt Thông 324
81
2/19/2014
Menu và Toolbar
Menus
(cid:1) MenuStrip
(cid:1) Menus
(cid:2) Display application commands and options grouped by functionality.
(cid:1) Context Menus
(cid:1) Toolbars
(cid:1) Status Bars
.NET Programming - Nguyễn Đạt Thông 325 .NET Programming - Nguyễn Đạt Thông 326
MenuStrip
Menus
(cid:1) Common Properties
Menu
(cid:2) Name: Indicates the name used in code to identify the menu. Usually set
Shortcut
key
mnu+text (e.g. mnuFile, mnuNew, mnuOpen,...).
(cid:2) Checked: Whether menu item appears checked. Default false, meaning that
Disabled
command
the menu item is not checked.
submenu
(cid:2) Shortcut: Shortcut key for the menu item (i.e. Ctrl + F9 can be equivalent to
clicking a specific item).
Separator bar
Checked
menu item
.NET Programming - Nguyễn Đạt Thông 327 .NET Programming - Nguyễn Đạt Thông 328
82
2/19/2014
MenuStrip
Context Menus
(cid:1) Common Properties
(cid:1) ContextMenuStrip
(cid:2) ShowShortcut: If true, shortcut key shown beside menu item text. Default
(cid:2) Display a shortcut menu when the user right-clicks the associated controls.
true.
(cid:2) Text: Text to appear on menu item. To make an Alt access shortcut, precede a
(cid:1) To display shortcut menu of the control
character with & (i.e. &File for File).
(cid:2) sets the ContextMenuStrip property of the control to the name of
ContextMenuStrip menu.
(cid:1) Common Events
(cid:2) Click: Occurs when item is clicked or shortcut key is used. Default when
double-clicked in designer.
.NET Programming - Nguyễn Đạt Thông 329 .NET Programming - Nguyễn Đạt Thông 330
Toolbars
Toolbars
(cid:1) ToolStrip contains buttons which are ToolStripMenuItem(s)
(cid:1) ToolStrip
(cid:2) Provide toolbars and other user interface elements that support many
appearance options, and that support overflow and runtime reordering.
with
(cid:2) Properties: Text, Image, Checked, DropDownItems
(cid:2) Events: Clicked
(cid:1) To add standard toolbars in the designer
(cid:1) Buttons of ToolStrip could be:
(cid:2) Create a ToolStrip control.
(cid:2) In the upper right corner of the ToolStrip, click the smart task arrow to display
the ToolStrip Tasks pane.
(cid:2) In the ToolStrip Tasks pane, choose Insert Standard Items
(cid:2) ToolStripButton
(cid:2) ToolStripSplitButton
(cid:2) ToolStripDropDownButton
(cid:2) ToolStripComboBox
(cid:2) ToolStripTextBox
(cid:2) ToolStripSeperator
(cid:2) ToolStripProgressBar
.NET Programming - Nguyễn Đạt Thông 331 .NET Programming - Nguyễn Đạt Thông 332
83
2/19/2014
Status Bars
Custom Controls
(cid:1) StatusStrip
(cid:1) To create controls that abstract away unimportant details and are
tailored for a specific type of data.
(cid:2) Display information to the user about the object being viewed, the object’s
components, or the object’s operations.
(cid:1) To create controls that provide entirely new functionality, or just
combine existing UI elements in a unique way.
(cid:1) To create controls with a distinct original look, or ones that mimic
popular controls in professional applications.
.NET Programming - Nguyễn Đạt Thông 333 .NET Programming - Nguyễn Đạt Thông 334
SubmitButton User Control
Types of Custom Controls
(cid:1) Inherited controls are generally powerful and flexible.
(cid:2) choose the existing .NET control that is closest to what we
want to provide.
(cid:1) User controls are the simplest type of control.
(cid:2) They inherit from System.Windows.Forms.UserControl class, and follow a
model of composition.
(cid:2) They combine more than one control in a logical unit (like a group of text boxes
for entering address information).
(cid:1) Owner-drawn controls generally use GDI+ drawing routines to
generate their interfaces from scratch.
.NET Programming - Nguyễn Đạt Thông 335 .NET Programming - Nguyễn Đạt Thông 336
84
2/19/2014
LoginValidation User Control
Một số ví dụ khác về User Control
.NET Programming - Nguyễn Đạt Thông 337 .NET Programming - Nguyễn Đạt Thông 338
Sự kiện Paint
Hàm OnPaint
(cid:1) The Paint event is raised when the control is redrawn.
(cid:1) The base Control class
(cid:2) does not know how a derived control needs to be drawn and
(cid:2) does not provide any painting logic in the OnPaint method.
(cid:1) It passes an instance of PaintEventArgs to the method(s) that
class MyCustomButton : Button {
handles the Paint event.
protected override void OnPaint(PaintEventArgs pevent) {
// call inherited function: to draw normal button
base.OnPaint(pevent);
// draw from scratch
pevent.Graphics.DrawEllipse(new Pen(Color.Red), 0, 0, Width, Height);
// subscribe to Paint event of button1
this.button1.Paint += new
System.Windows.Forms.PaintEventHandler(this.button1_Paint);
}
}
class MyNewButton : Button {
private void button1_Paint(object sender, PaintEventArgs e)
{
protected override void OnPaint(PaintEventArgs pevent) {
Control ctrl = sender as Control;
Point center = new Point(ctrl.Width / 2, ctrl.Height / 2);
// do not call inherited function
// base.OnPaint(pevent);
// draw from scratch
pevent.Graphics.DrawEllipse(new Pen(Color.Red), 0, 0, Width, Height);
// draw a rectangle at center of button
e.Graphics.DrawRectangle(new Pen(Color.Red),
}
}
center.X - 50, center.Y - 15, // X and Y
100, 30 // Width and Height
);
}
.NET Programming - Nguyễn Đạt Thông 339 .NET Programming - Nguyễn Đạt Thông 340
85
2/19/2014
Một số ví dụ về vẽ Controls
Một số ví dụ về giao diện “Luxury”
.NET Programming - Nguyễn Đạt Thông 341 .NET Programming - Nguyễn Đạt Thông 342
Một số ví dụ về giao diện “Luxury”
Ghi chú
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
.NET Programming - Nguyễn Đạt Thông 343 .NET Programming - Nguyễn Đạt Thông 344
86
2/19/2014
Đa luồng
(cid:1) Threading
(cid:1) Control threads
Chương 4
(cid:1) Synchronize between threads
(cid:1) UI thread
.NET Programming - Nguyễn Đạt Thông 345 .NET Programming - Nguyễn Đạt Thông 346
Luồng – Threading
Đa luồng – Multi-threading
(cid:1) Threading
(cid:1) Multithreading
(cid:2) enables a C# program to perform concurrent processing so it can do more than
(cid:2) solves problems with responsiveness and multi-tasking.
one operation at a time.
(cid:1) Multithreading
(cid:1) The System.Threading namespace (in mscorlib.dll) provides
(cid:2) introduces resource sharing and synchronization issues.
classes and interfaces that support multithreaded programming:
(cid:2) creating and starting new threads,
(cid:2) synchronizing multiple threads,
(cid:2) suspending threads,
(cid:2) and aborting threads.
.NET Programming - Nguyễn Đạt Thông 347 .NET Programming - Nguyễn Đạt Thông 348
87
2/19/2014
Ưu điểm
Nhược điểm
(cid:1) Communicate over a network, to a Web server, and to a database.
(cid:1) The system consumes memory for the context information required
by processes.
(cid:1) Perform operations that take a large amount of time.
(cid:1) Keeping track of a large number of threads consumes significant
processor time.
(cid:1) Distinguish tasks of varying priority: high-priority thread manages
time-critical tasks, and low-priority thread performs other tasks.
(cid:1) Controlling code execution with many threads is complex.
(cid:1) Allow the user interface to remain responsive, while allocating time to
background tasks.
(cid:1) Destroying threads requires knowing what could happen and
handling those issues.
.NET Programming - Nguyễn Đạt Thông 349 .NET Programming - Nguyễn Đạt Thông 350
Lớp Thread
Lớp Thread
(cid:1) Properties
(cid:1) Creates and controls a thread, sets its priority, and gets its status.
(cid:1) Thread is sealed.
(cid:2) ThreadState
(cid:2) IsAlive
(cid:2) ThreadPriority
(cid:1) Use a ThreadStart delegate to specify the program code executed
(cid:1) Methods
by a thread.
(cid:2) Start(), Resume()
(cid:2) Interrupt(), Abort()
(cid:1) Static members
(cid:2) CurrentThread,
(cid:2) Sleep()
.NET Programming - Nguyễn Đạt Thông 351 .NET Programming - Nguyễn Đạt Thông 352
88
2/19/2014
ThreadStart delegate
Thread: Ví dụ
(cid:1) Represents the method that executes on the Thread.
using System;
using System.Threading;
public class ThreadExample {
public static void ThreadProc() {
for (int i = 0; i < 10; i++) {
(cid:1) Delegate declaration:
Console.WriteLine("ThreadProc: {0}", i);
Thread.Sleep(100);
}
(cid:2) public delegate void ThreadStart();
}
public static void Main() {
(cid:1) The declaration of your callback method must have the same
Console.WriteLine("Main thread: Start a second thread.");
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
parameters as the ThreadStart delegate declaration.
for (int i = 0; i < 4; i++) {
Console.WriteLine("Main thread: Do some work.");
Thread.Sleep(100);
}
Console.WriteLine("Main thread: Call Join().");
t.Join();
Console.WriteLine("Main thread: Join has returned.");
Console.ReadLine();
}
}
.NET Programming - Nguyễn Đạt Thông 353 .NET Programming - Nguyễn Đạt Thông 354
Truyền và nhận thông tin từ thread
Truyền thông tin cho thread
(cid:1) The ThreadStart delegate
(cid:1) Create a class ThreadWithData to hold the data Data and the
(cid:2) has no parameters or return value.
thread method ThreadProc.
(cid:1) User cannot
(cid:1) Create an object of ThreadWithData class with desired Data.
(cid:2) start a thread using a method that takes parameters, or
(cid:2) obtain a return value from the method.
(cid:1) Create a thread with ThreadStart delegate “ThreadProc”.
(cid:1) To pass data to a thread
(cid:1) Once ThreadProc is called, access the Data.
(cid:2) create an object to hold the data and the thread method.
(cid:1) To retrieve the results of a thread method
(cid:2) we can use a callback method.
.NET Programming - Nguyễn Đạt Thông 355 .NET Programming - Nguyễn Đạt Thông 356
89
2/19/2014
Truyền thông tin: Ví dụ
Nhận kết quả từ thread
(cid:1) Create a class ThreadWithCallback to hold the delagate
ResultHandler and the thread method ThreadProc.
using System;
using System.Threading;
public class ThreadWithData {
private string Data;
public ThreadWithData(string data) {
Data = data;
(cid:1) Create an object of ThreadWithCallback class with desired
}
public void ThreadProc() {
Callback.
Console.WriteLine("Do work with argument: Hello {0}.", Data);
}
}
public class Example {
(cid:1) Create a thread with ThreadStart delegate “ThreadProc”.
public static void Main() {
ThreadWithData twd = new ThreadWithData("C# World");
Thread t = new Thread(new ThreadStart(twd.ThreadProc));
t.Start();
(cid:1) Once ThreadProc is finished, call the Callback.
Console.WriteLine("Main thread does some work, then waits.");
t.Join();
Console.WriteLine("Independent task has completed.");
Console.ReadLine();
}
}
.NET Programming - Nguyễn Đạt Thông 357 .NET Programming - Nguyễn Đạt Thông 358
Nhận kết quả: Ví dụ
Điều khiển các thread
public delegate void ResultHandler(string result);
public class ThreadWithCallback {
(cid:1) Pausing a thread
private string Data;
private ResultHandler Callback;
public ThreadWithCallback(string data, ResultHandler callback) {
Data = data;
Callback = callback;
(cid:1) Suspend a thread
}
public void ThreadProc() {
(cid:1) Resume a thread
Console.WriteLine("Do work with argument: {0}.", Data);
string Result = "Hello " + Data;
if (Callback != null)
Callback(Result);
}
}
public class ExampleCallback {
(cid:1) Stopping a thread
public static void Main() {
ThreadWithCallback twc = new ThreadWithCallback("C# World", resultCallback);
Thread t = new Thread(new ThreadStart(twc.ThreadProc));
t.Start();
Console.WriteLine("Main thread does some work, then waits.");
t.Join();
Console.WriteLine("Independent task has completed."); Console.ReadLine();
}
private static void resultCallback(string result) {
Console.WriteLine("Handle the result '{0}' here...", result);
}
}
.NET Programming - Nguyễn Đạt Thông 359 .NET Programming - Nguyễn Đạt Thông 360
90
2/19/2014
Tạm ngưng một thread
Tạm dừng một thread
(cid:1) We can pause a thread by calling Thread.Suspend.
(cid:1) After a thread has been started, we often want to pause that thread
for a fixed period of time.
(cid:1) When a thread calls Suspend on itself,
(cid:1) Calling Thread.Sleep causes the current thread to immediately
(cid:2) the call blocks until the thread is resumed by another thread.
block for the number of milliseconds.
(cid:1) When one thread calls Suspend on another thread,
(cid:1) One thread cannot call Sleep on another thread.
(cid:2) the call is a non-blocking call that causes the other thread to pause.
.NET Programming - Nguyễn Đạt Thông 361 .NET Programming - Nguyễn Đạt Thông 362
Tạm dừng một thread
Tiếp tục một thread
(cid:1) We can call Suspend many times on a thread.
(cid:1) Calling Thread.Resume
(cid:2) breaks another thread out of the suspend state and
(cid:2) causes the thread to resume execution.
(cid:1) A thread cannot be suspended
(cid:2) if it has not been started or if it has stopped.
(cid:1) The thread will resume
(cid:2) regardless of how many times Thread.Suspend was called.
(cid:1) Suspend does not cause a thread to immediately stop execution.
(cid:2) The CLR must wait until the thread has reached a safe point before it can
suspend the thread.
(cid:1) The thread resumes execution immediately following the call to
Resume.
.NET Programming - Nguyễn Đạt Thông 363 .NET Programming - Nguyễn Đạt Thông 364
91
2/19/2014
Dừng hẳn thread
Ghi chú
(cid:1) We can block threads in a number of ways:
(cid:2) Thread.Join
(cid:2) Thread.Sleep
(cid:2) Synchronized object
(cid:1) We can interrupt a waiting thread
(cid:2) by calling Thread.Interrupt on the blocked thread to throw a
ThreadInterruptedException, which breaks the thread out of the blocking
call.
(cid:1) Thread.Abort is similar to Thread.Interrupt
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
(cid:2) except that it causes ThreadAbortException.
.NET Programming - Nguyễn Đạt Thông 365 .NET Programming - Nguyễn Đạt Thông 366
Đồng bộ hóa các thread
Đồng bộ hóa
(cid:1) One of the benefits of using multiple threads in an application
(cid:1) Thread synchronization in C# can be accomplished by using:
(cid:2) lock statement
(cid:2) is that each thread executes asynchronously.
(cid:2) Monitor class
(cid:1) Those threads asynchronously access to resources
(cid:2) such as file handles, network connections, and memory must be coordinated.
(cid:2) Synchronization events
(cid:1) They could access the same resource at the same time, each
(cid:2) Mutex class
unaware of the other's actions.
(cid:2) The result is unpredictable data corruption.
.NET Programming - Nguyễn Đạt Thông 367 .NET Programming - Nguyễn Đạt Thông 368
92
2/19/2014
Câu lệnh lock
Câu lệnh lock
(cid:1) The lock keyword
(cid:1) The argument provided to the lock keyword must be an object.
(cid:2) can be used to ensure that a block of code runs to completion without
interruption by other threads.
(cid:1) Many types provide a SyncRoot member to use by lock statement.
(cid:1) This is accomplished by obtaining a mutual-exclusion lock
(cid:2) for a given object for the duration of the code block.
public class TestThreading {
private Object lockThis = new Object();
public void Function() {
lock (lockThis) {
// Access thread-sensitive resources.
}
(cid:1) A lock statement
}
(cid:2) begins with the keyword lock, and
(cid:2) followed by a code block.
.NET Programming - Nguyễn Đạt Thông 369 .NET Programming - Nguyễn Đạt Thông 370
Lớp Monitor
Lớp Monitor
(cid:1) Like the lock keyword, monitors prevent blocks of code from
(cid:1) The Enter method
simultaneous execution by multiple threads.
(cid:2) allows one and only one thread to proceed into the following statements;
(cid:2) all other threads are blocked until the executing thread calls Exit.
(cid:1) In fact, the lock keyword is implemented with the Monitor class :
System.Object obj = (System.Object)x;
System.Threading.Monitor.Enter(obj);
try {
(cid:2) lock is more concise,
(cid:2) lock insures that the underlying monitor is released, even if the protected code
DoSomething();
throws an exception.
}
finally {
System.Threading.Monitor.Exit(obj);
}
.NET Programming - Nguyễn Đạt Thông 371 .NET Programming - Nguyễn Đạt Thông 372
93
2/19/2014
Các sự kiện đồng bộ hóa
Các sự kiện đồng bộ hóa
(cid:1) lock and Monitor
(cid:1) Threads can be suspended
(cid:2) do not allow one thread to communicate an event to another.
(cid:2) by being made to wait on a synchronization event that is un-signaled.
(cid:1) This requires synchronization events,
(cid:1) Threads can be activated
(cid:2) by changing the event state to signaled.
(cid:2) which are objects that have one of two states, signaled and un-signaled,
(cid:2) that can be used to activate and suspend threads.
(cid:1) If a thread attempts to wait on an event that is already signaled,
(cid:2) then the thread continues to execute without delay.
.NET Programming - Nguyễn Đạt Thông 373 .NET Programming - Nguyễn Đạt Thông 374
Các sự kiện đồng bộ hóa
Các sự kiện đồng bộ hóa
(cid:1) There are two kinds of synchronization events
(cid:1) Threads can be made to wait on events by calling one of the wait
(cid:2) AutoResetEvent
(cid:2) ManualResetEvent
methods
(cid:2) System.Threading.WaitHandle.WaitOne
○ causes the thread to wait until a single event becomes signaled,
(cid:1) AutoResetEvent
(cid:2) changes from signaled to un-signaled automatically any time it activates a
(cid:2) System.Threading.WaitHandle.WaitAny
thread.
○ blocks a thread until one or more indicated events become signaled,
(cid:1) ManualResetEvent
(cid:2) System.Threading.WaitHandle.WaitAll
(cid:2) allows any number of threads to be activated by its signaled state, and will only
○ blocks the thread until all of the indicated events become signaled.
revert to an un-signaled state when its Reset method is called.
(cid:1) An event becomes signaled when its Set method is called.
.NET Programming - Nguyễn Đạt Thông 375 .NET Programming - Nguyễn Đạt Thông 376
94
2/19/2014
Lớp Mutex
Đồng bộ hóa: Ví dụ
class ThreadingExample {
(cid:1) A mutex is similar to a monitor;
(cid:2) it prevents the simultaneous execution of a block of code by more than one
static AutoResetEvent autoEvent;
static ManualResetEvent manualEvent;
static void DoWork() {
thread at a time.
Console.WriteLine("worker thread started, now waiting on event...");
autoEvent.WaitOne();
Console.WriteLine("worker thread reactivated, now exiting...");
}
static void DoAnotherWork() {
(cid:1) A Mutex can be used to synchronize threads across processes.
Console.WriteLine("another worker thread started, now waiting on event...");
manualEvent.WaitOne();
Console.WriteLine("another worker thread reactivated, now exiting...");
}
static void Main() {
(cid:1) When used for inter-process synchronization, a Mutex is called a
named mutex.
(cid:2) It must be given a name so that both applications can access the same Mutex
autoEvent = new AutoResetEvent(false);
manualEvent = new ManualResetEvent(true);
Console.WriteLine("main thread starting worker thread...");
Thread t = new Thread(DoWork), t2 = new Thread(DoAnotherWork);
t.Start(); t2.Start();
object.
Console.WriteLine("main thrad sleeping for 1 second...");
Thread.Sleep(1000);
Console.WriteLine("main thread signaling worker thread...");
autoEvent.Set();
}
}
.NET Programming - Nguyễn Đạt Thông 377 .NET Programming - Nguyễn Đạt Thông 378
Mutex: Ví dụ
UI thread
(cid:1) An UI based application is frozen in a long time when it’s
using System;
using System.Threading;
namespace TestMutex {
class ExampleMutex {
static void Main1() {
Mutex mutex = null;
try {
mutex = Mutex.OpenExisting("Our shared mutex");
}
catch (System.Threading.WaitHandleCannotBeOpenedException e) {
(cid:2) making a long database operation
(cid:2) or calling a long running service
(cid:2) or making any network connections
(cid:2) or reading a large file from CD drive, etc.
mutex = new Mutex(false, "Our shared mutex");
}
while (mutex.WaitOne(1000) == false)
Console.WriteLine("Mutex is own by another program... Try again.");
(cid:1) The reason is that the program has only 1 thread to listen to user
Console.WriteLine("We obtained the mutex...");
for (int i = 0; i < 10; i++) {
operations and do the underlying tasks.
(cid:2) When doing the tasks, the thread cannot handle user operations and the UI is
Console.WriteLine("Do some works...");
Thread.Sleep(1000);
frozen.
}
mutex.ReleaseMutex();
Console.ReadLine();
}
}
}
.NET Programming - Nguyễn Đạt Thông 379 .NET Programming - Nguyễn Đạt Thông 380
95
2/19/2014
Worker threads
Đồng bộ hóa giao diện
(cid:1) The solution is
(cid:1) Controls in Windows Forms
(cid:2) create “worker” threads to perform the tasks while the UI thread continues
(cid:2) are bound to a specific thread (UI thread) and are not thread safe.
listening to user operations.
(cid:1) If you are calling a control's method from a different thread,
(cid:1) Once the worker threads finished, or they want to update working
(cid:2) you must use one of the control's invoke methods to marshal the call to the
proper thread.
status to the UI (such as progress bar)
(cid:2) they could notify the UI thread.
(cid:1) To executes a delegate on the thread that owns the control's
(cid:1) The worker thread cannot call methods of UI controls directly,
(cid:2) they must use UI thread synchronization.
underlying window handle (GUI thread)
(cid:2) Control.Invoke()
(cid:2) Control.BeginInvoke() and Control.EndInvoke()
.NET Programming - Nguyễn Đạt Thông 381 .NET Programming - Nguyễn Đạt Thông 382
Invoke: Ví dụ
Ghi chú
(cid:1) Control.InvokeRequired
(cid:2) returns a value indicating whether the caller must call an invoke method when
making method calls to the control.
using System;
public delegate void ProgressBarUpdater();
public class WorkerThread {
private System.Windows.Forms.ProgressBar ProgressBar;
public WorkerThread(System.Windows.Forms.ProgressBar progressBar) {
ProgressBar = progressBar;
}
public void ThreadProc() {
for (int i = 0; i < 100; i++) {
Console.WriteLine("we have done {0}% of the task.", i);
if (ProgressBar.InvokeRequired) {
ProgressBarUpdater updater = delegate() {
ProgressBar.Value = i;
};
ProgressBar.Invoke(updater);
}
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
}
}
}
.NET Programming - Nguyễn Đạt Thông 383 .NET Programming - Nguyễn Đạt Thông 384
96
2/19/2014
Kết nối mạng
IP Address
(cid:1) .NET defines two classes in the System.Net namespace to handle
(cid:1) IP Addresses
(cid:1) Sockets
various types of IP address information
(cid:2) IPAddress: is used to represent a single IP address.
(cid:2) IPEndPoint: is used when binding sockets to local addresses, or when
connecting sockets to remote addresses
(cid:1) Connection-Oriented Sockets
(cid:1) .NET also defines System.Net.Dns class for looking up IP
(cid:1) Networking and Multi-threading
addresses from domain (host) name.
.NET Programming - Nguyễn Đạt Thông 385 .NET Programming - Nguyễn Đạt Thông 386
Lớp IPAddress
Lớp IPEndPoint
Method
Method
Description
Equals
Compares two IP addresses.
Create
Description
Creates an EndPoint object from a
SocketAddress object
HostToNetworkOrder Converts an IP address from host byte order
Equals
Compares two IPEndPoint objects.
to network byte order.
Serialize
IsLoopBack
Creates a SocketAddress instance of the
IPEndPoint instance
Indicates whether the IP address is
considered the loopback address.
ToString
NetworkToHostOrder Converts an IP address from network byte
Creates a string representation of the
IPEndPoint instance
order to host byte order.
Description
Parse
Property
Address
Gets or sets the IP address property
Converts a string to an IPAddress
instance.
AddressFamily
Gets the IP address family
Port
Gets or sets the TCP or UDP port number
ToString
Converts an IPAddress to a string
representation of the dotted decimal format
of the IP address.
.NET Programming - Nguyễn Đạt Thông 387 .NET Programming - Nguyễn Đạt Thông 388
97
2/19/2014
Lớp Dns
Ví dụ
using System;
using System.Net;
class IPEndPointSample {
Method
Description
public static void Main() {
GetHostName
Gets the host name of the local computer.
IPAddress test1 = IPAddress.Parse("192.168.1.1");
IPEndPoint ie = new IPEndPoint(test1, 8000);
Console.WriteLine("The IPEndPoint is: {0}", ie.ToString());
Console.WriteLine("The AddressFamily is: {0}", ie.AddressFamily);
Console.WriteLine("The address is: {0}, and the port is: {1}\n",
Resolve
ie.Address, ie.Port);
Resolves a DNS host name or IP address to
an System.Net.IPHostEntry instance
Console.WriteLine("The min port number is: {0}", IPEndPoint.MinPort);
Console.WriteLine("The max port number is: {0}\n", IPEndPoint.MaxPort);
GetHostEntry
Resolves a host name or IP address to an
System.Net.IPHostEntry instance.
ie.Port = 80;
Console.WriteLine("The changed IPEndPoint value is: {0}", ie.ToString());
SocketAddress sa = ie.Serialize();
Console.WriteLine("The SocketAddress is: {0}", sa.ToString());
}
}
.NET Programming - Nguyễn Đạt Thông 389 .NET Programming - Nguyễn Đạt Thông 390
Tạo một Socket
Sockets
(cid:1) The System.Net.Sockets namespace
SocketType
ProtocolType
Description
(cid:2) contains the classes that provide the actual .NET interface to the low-level
Dgram
Udp
Connectionless communication
Winsock APIs.
Stream
Tcp
Connection-oriented
communication
(cid:1) The Socket class
Raw
Icmp
(cid:2) is the core of the System.Net.Sockets namespace.
Internet Control Message
Protocol
Raw
Raw
Plain IP packet communication
(cid:1) To construct a Socket, use following constructor
(cid:1) Example
public Socket(AddressFamily addressFamily,
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType socketType,
ProtocolType protocolType);
SocketType.Stream,
ProtocolType.Tcp);
.NET Programming - Nguyễn Đạt Thông 391 .NET Programming - Nguyễn Đạt Thông 392
98
2/19/2014
Thuộc tính của Socket
Connection-Oriented Sockets
(cid:1) Server functions
Property
Description
AddressFamily
Gets the address family of the Socket
(cid:2) Bind()
(cid:2) Listen()
(cid:2) Accept()
Available
Gets the amount of data that is ready to be read
Blocking
Gets or sets whether the Socket is in blocking mode
(cid:1) Client functions
(cid:2) Connect()
Connected
Gets a value that indicates if the Socket is
connected to a remote device
LocalEndPoint
Gets the local EndPoint object for the Socket
(cid:1) Server and Client functions
ProtocolType
Gets the protocol type of the Socket
RemoteEndPoint
Gets the remote EndPoint information for the
Socket
(cid:2) Send()
(cid:2) Receive()
(cid:2) Close()
SocketType
Gets the type of the Socket
.NET Programming - Nguyễn Đạt Thông 393 .NET Programming - Nguyễn Đạt Thông 394
Server: Ví dụ
Client: Ví dụ
using System;
using System.Net;
using System.Net.Sockets;
class ListenSample {
public static void Main() {
using System;
using System.Net;
using System.Net.Sockets;
class ConnectSample {
public static void Main() {
IPHostEntry local = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint iep = new IPEndPoint(local.AddressList[1], 8000);
// second address is IPv6
IPAddress host = IPAddress.Parse("192.168.167.87");
IPEndPoint hostep = new IPEndPoint(host, 8000);
Socket newserver = new Socket(AddressFamily.InterNetwork,
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
SocketType.Stream, ProtocolType.Tcp);
newserver.Bind(iep);
newserver.Listen(5);
Console.WriteLine("Connecting to server...");
try {
Console.WriteLine("Listen on {0}. Waiting for clients...",
newserver.LocalEndPoint);
sock.Connect(hostep);
Console.WriteLine("Server Connected.");
Socket newclient = newserver.Accept();
Console.WriteLine("New client connected: {0}", newclient.RemoteEndPoint);
}
catch (Exception e) {
}
Console.WriteLine("Cannot connect to server: {0}", e.Message);
}
}
}
}
.NET Programming - Nguyễn Đạt Thông 395 .NET Programming - Nguyễn Đạt Thông 396
99
2/19/2014
Giao tiếp Server-Client
Giao tiếp Server-Client
class ConnectSample {
public static void Main() {
class ListenSample {
public static void Main() {
// ...
try {
// ...
try {
Console.WriteLine("Say hello to server...");
string hello = "Hello from client.";
byte[] btHello = System.Text.Encoding.Default.GetBytes(hello);
sock.Send(btHello);
Console.WriteLine("Waiting for message from client...");
byte[] btMsg = new byte[1024];
newclient.Receive(btMsg);
string msg = System.Text.Encoding.Default.GetString(btMsg);
Console.WriteLine("Receive: {0}", msg);
byte[] btReply = new byte[1024];
sock.Receive(btReply);
string reply = System.Text.Encoding.Default.GetString(btReply);
Console.WriteLine("Reply from server: {0}", reply);
string hello = "Hello from Server.";
byte[] btHello = System.Text.Encoding.Default.GetBytes(hello);
newclient.Send(btHello);
}
catch (Exception e) {
}
catch (Exception e) {
Console.WriteLine("Network error: {0}", e.Message);
Console.WriteLine("Network error: {0}", e.Message);
}
}
}
}
}
}
.NET Programming - Nguyễn Đạt Thông 397 .NET Programming - Nguyễn Đạt Thông 398
Lớp TcpClient
Các lớp tiện ích Socket
(cid:1) The methods of the TcpClient class are used to
(cid:1) The .NET Framework provides a simplified interface for easier
network programming.
(cid:2) create client network programs that follow the connection-oriented network
model.
(cid:1) Three helper classes in System.Net.Sockets namespace are
(cid:1) The TcpClient methods mirror those in normal socket
programming
(cid:2) but many of the steps are compacted to simplify the programming task.
used for socket programming
(cid:2) TcpClient
(cid:2) TcpListener
(cid:2) UdpClient
TcpClient newclient = new TcpClient("www.isp.net", 8000);
NetworkStream ns = newclient.GetStream();
byte[] outbytes = Encoding.ASCII.GetBytes("Testing");
ns.Write(outbytes, 0, outbytes.Length);
byte[] inbytes = new byte[1024];
ns.Read(inbytes, 0, inbytes.Length);
string instring = Encoding.ASCII.GetString(inbytes);
ns.Close();
newclient.Close();
.NET Programming - Nguyễn Đạt Thông 399 .NET Programming - Nguyễn Đạt Thông 400
100
2/19/2014
Lớp TcpListener
Lớp UdpClient
(cid:1) The TcpListener class simplifies server programs
(cid:1) For applications that require a connectionless socket
(cid:2) the UdpClient class provides a simple interface to UDP sockets.
(cid:1) After the Start() method
(cid:1) The Receive() method
(cid:2) use either the AcceptSocket()
(cid:2) or AcceptTcpClient() method to accept incoming connection attempts.
(cid:2) allows you to receive data on the UDP port.
TcpListener newserver = new TcpListener(9050);
newserver.Start();
UdpClient newconn = new UdpClient(8000);
IPEndPoint
remoteclient = new IPEndPoint(IPAddress.Any, 0);
byte[] recv = newconn.Receive(ref remoteclient);
string data = Encoding.ASCII.GetString(recv);
TcpClient newclient = newserver.AcceptTcpClient();
NetworkStream ns = newclient.GetStream();
byte[] outbytes = Encoding.ASCII.GetBytes("Testing");
ns.Write(outbytes, 0, outbytes.Length);
byte[] inbytes = new byte[1024];
ns.Read(inbytes, 0, inbytes.Length);
string instring = Encoding.ASCII.GetString(inbytes);
ConsoleWriteLine("From: {0}", remoteclient.ToString());
ConsoleWriteLine(" Data: {0}", data);
newconn.Close();
ns.Close();
newclient.Close();
newserver.Stop();
.NET Programming - Nguyễn Đạt Thông 401 .NET Programming - Nguyễn Đạt Thông 402
Đa luồng và kết nối mạng
Đa luồng và kết nối mạng
Main Program
Server
Main Program
Thread
Thread
Thread
Thread
• Create Socket
• Bind Socket
• Listen on Socket
• While {
• accept connection
clientSock
Client Thread
• create thread
• While {
Network
with parameter
clientSock
}
• Receive request
from clientSock
• Send response to
clientSock
}
Client
Client
Client
Client
.NET Programming - Nguyễn Đạt Thông 403 .NET Programming - Nguyễn Đạt Thông 404
101
2/19/2014
Đa luồng và đa kết nối
Đa luồng và đa kết nối
Main Program
Server
Main Program
• Create Socket
• Bind Socket
• Listen on Socket
• While {
Thread
Thread
Thread
Thread
• accept connection
clientSock
Client Thread
• create thread
• While {
• receive request from
with parameter
clientSock
clientSock
Network
• send response to
• store clientSock
in client list
clientSock
}
• send request to
partner(s) of clientSock
}
Client
Client
Client
Client
.NET Programming - Nguyễn Đạt Thông 405 .NET Programming - Nguyễn Đạt Thông 406
Đa luồng, đa kết nối, và giao diện
Đa luồng, đa kết nối, và giao diện
UI Thread
Server
UI Thread
Listening Thread
Listening Thread
• Start GUI
• Start Listening Thread
• While {
• Hanlde UI event
Thread
Thread
Thread
Thread
}
• Create Socket
• Bind Socket
• Listen on Socket
• While {
• accept connection
clientSock
Client Thread
• create thread with
Network
• While {
parameter clientSock
• store clientSock in
• receive request from
client list
clientSock
}
• send response to
clientSock
Client
Client
Client
Client
• send request to
partner(s) of clientSock
UI Thread
UI Thread
UI Thread
UI Thread
}
.NET Programming - Nguyễn Đạt Thông 407 .NET Programming - Nguyễn Đạt Thông 408
102
2/19/2014
Tóm lược
Tóm lược
(cid:1) How to create threads to do background tasks?
(cid:1) How to create a server to listen to clients?
(cid:1) How to control worker threads?
(cid:1) How to connect to remote servers?
(cid:1) How to pass data and retrieve result from threads?
(cid:1) How to communicate between clients and servers?
(cid:1) How to synchronize between threads?
(cid:1) How to use socket helper classes?
(cid:1) How to create worker threads for UI program?
(cid:1) How to create a multi-threading network server?
.NET Programming - Nguyễn Đạt Thông 409 .NET Programming - Nguyễn Đạt Thông 410
Tham khảo thêm
Tham khảo thêm
(cid:1) Tutorial: Threading
(cid:1) Thread and Threading
http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx
http://msdn.microsoft.com/en-us/library/aa720724(v=vs.71).aspx
(cid:1) Control.Invoke method
(cid:1) Tutorial: Thread Synchronization
http://msdn.microsoft.com/en-us/library/ms173179(v=vs.80).aspx
http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx
http://msdn.microsoft.com/en-us/library/a1hetckb.aspx
(cid:1) UI thread and Worker thread
http://www.codeproject.com/Articles/81411/Thread-Synchronization-UI-Thread-and-Worker-
Thread
.NET Programming - Nguyễn Đạt Thông 411 .NET Programming - Nguyễn Đạt Thông 412
103
2/19/2014
Tham khảo thêm
Ghi chú
(cid:1) How to C# Socket programming
http://csharp.net-informations.com/communications/csharp-socket-programming.htm
(cid:1) C# Network Programming – Richard Blum
http://www.ccse.kfupm.edu.sa/~fazzedin/COURSES/CSP2005/Reading/NetworkProgrammi
ng.pdf
(cid:1) WebClient Class
http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.80).aspx
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
.NET Programming - Nguyễn Đạt Thông 413 .NET Programming - Nguyễn Đạt Thông 414
ADO .NET
(cid:1) Connections
(cid:1) Commands & Data Readers
Chương 5
(cid:1) Disconnected Data Sets
(cid:1) Database Independent Coding
.NET Programming - Nguyễn Đạt Thông 415 .NET Programming - Nguyễn Đạt Thông 416
104
2/19/2014
ADO .NET
Kết nối cơ sở dữ liệu
(cid:1) ADO.NET provides managed types for database access
(cid:1) Must specify several pieces of information to connect
(cid:2) generic types in System.Data namespace,
(cid:2) SQL Server types in System.Data.SqlClient namespace,
(cid:2) other data providers also supported.
(cid:2) server
(cid:2) database
(cid:2) authentication credentials
(cid:1) Exact connection details differ for different providers
.NET Programming - Nguyễn Đạt Thông 417 .NET Programming - Nguyễn Đạt Thông 418
Server và Database
Chứng thực
(cid:1) Use Server parameter to specify server for SQL Server
(cid:1) Two ways to authenticate a client connection for SQL Server
(cid:2) Windows authentication uses Windows user information
○ IntegratedSecurity set to SSPI in connect string.
(cid:2) passed in connect string.
(cid:2) use "." or "localhost" to connect to local database.
string connectString = "Server=localhost;...";
string connectString = "Integrated Security=SSPI;...";
(cid:1) Use Database parameter to specify database for SQL Server
(cid:2) SQL Server authentication uses SQL Server user information
(cid:2) passed in connect string
○ UserID and Password passed in connect string.
string connectString = "User ID=Joe; Password=lobster;...";
string connectString = "Database=pubs;...";
.NET Programming - Nguyễn Đạt Thông 420 .NET Programming - Nguyễn Đạt Thông 419
105
2/19/2014
Mở một kết nối
Ngắt kết nối
(cid:1) Close SqlConnection when finished.
Application
SqlConnection
Database
(cid:2) can call either Close() or Dispose() method
(cid:2) typical to place call in finally block or using statement.
(cid:1) Use System.Data.SqlClient.SqlConnection to connect to
static void Main() {
System.Data.SqlClient.SqlConnection connection = null;
try {
SQL Server
(cid:2) create object
(cid:2) specify connect string
//...
// open connection
connection.Open();
//...
}
finally {
○ can pass to constructor
○ can set after creation using ConnectionString property.
// close connection
connection.Dispose();
}
(cid:1) Call Open() method
}
string cs = "server=.;Integrated Security=SSPI;database=pubs";
System.Data.SqlClient.SqlConnection connection =
new System.Data.SqlClient.SqlConnection(cs);
connection.Open();
.NET Programming - Nguyễn Đạt Thông 421 .NET Programming - Nguyễn Đạt Thông 422
ExecuteReader
Commands và Readers
ExecuteReader
Application
SqlCommand
SqlConnection
Database
Application
Database
Sql
Command
Sql
Connection
SqlDataReader
(cid:1) SqlCommand is used to execute a command
(cid:1) Use ExecuteReader() when result set expected
(cid:2) must specify command text
○ can pass to constructor
○ can set after creation using CommandText property
(cid:2) must specify connection to use
(cid:2) returned data placed in SqlDataReader object
(cid:2) reader provides forward-only access to data
(cid:2) multiple results supported using NextResult
(cid:2) throws Exception if command fails
○ can pass to constructor
○ can set after creation using Connection property
System.Data.SqlClient.SqlConnection connection =
new SqlConnection(/*...*/);
string text = "select * from authors";
System.Data.SqlClient.SqlConnection connection =
new System.Data.SqlClient.SqlConnection(/*...*/);
System.Data.SqlClient.SqlCommand command =
new System.Data.SqlClient.SqlCommand(text, connection);
// ...
string text = "select * from authors";
// create command
System.Data.SqlClient.SqlCommand command =
// ...
System.Data.SqlClient.SqlDataReader reader = // capture returned data
new System.Data.SqlClient.SqlCommand(text, connection);
command.ExecuteReader(); // execute command
.NET Programming - Nguyễn Đạt Thông 423 .NET Programming - Nguyễn Đạt Thông 424
106
2/19/2014
SqlDataReader
SqlDataReader
(cid:1) Call Close() when finished with SqlDataReader
(cid:1) Two main ways to access rows of result set
(cid:2) use foreach to traverse rows of IDataRecord objects
(cid:2) use while loop with Read to manually advance through rows
(cid:2) releases connection (which can then be reused)
(cid:2) can not access contained data after closing.
string text = "select * from authors";
System.Data.SqlClient.SqlConnection connection =
(cid:1) Three main ways to access columns of a row
new System.Data.SqlClient.SqlConnection(/*...*/);
System.Data.SqlClient.SqlCommand command =
new System.Data.SqlClient.SqlCommand(text, connection);
// ...
System.Data.SqlClient.SqlDataReader reader = command.ExecuteReader();
(cid:2) index by column ordinal or name
(cid:2) pass column index to getXXX methods
(cid:2) use for loop with FieldCount to access each column in turn
// loop through rows
while (reader.Read()) {
// ...
// close reader when finished
reader.Close();
// access data in row using indexers
string last = (string)reader["au_lname"];
string first = (string)reader[2];
// access data in row using GetXXX methods
string zip = reader.GetString(7);
// ...
}
.NET Programming - Nguyễn Đạt Thông 425 .NET Programming - Nguyễn Đạt Thông 426
ExecuteNonQuery
Store Procedures
ExecuteNonQuery
(cid:1) SqlCommand is used to execute stored procedure
Application
Database
Sql
Command
Sql
Connection
int
(cid:1) ExecuteNonQuery is used when no data will be returned
(cid:2) set CommandType property to StoredProcedure
(cid:2) set CommandText property to procedure name
(cid:2) pass parameters in Parameters collection
(cid:2) call ExecuteReader
(cid:2) returns an int specifying number of rows affected
System.Data.SqlClient.SqlCommand command =
new System.Data.SqlClient.SqlCommand("byroyalty", connection);
string text = "insert into authors "
// set command type to 'StoreProcedure'
command.CommandType = System.Data.CommandType.StoredProcedure;
+ "(au_id, au_lname, au_fname, contract) values "
+ "('111-11-1111', 'Adams', 'Mark', 1)";
System.Data.SqlClient.SqlCommand command =
// set parameters for store procedure
command.Parameters.Add("@percentage", System.Data.SqlDbType.Int);
command.Parameters["@percentage"].Value = 50;
new System.Data.SqlClient.SqlCommand(text, connection);
// execute the store procedure
reader = command.ExecuteReader();
// execute command
int rowsAffected = command.ExecuteNonQuery();
.NET Programming - Nguyễn Đạt Thông 427 .NET Programming - Nguyễn Đạt Thông 428
107
2/19/2014
DataSet & DataTable
Dữ liệu “Disconnected”
(cid:1) DataSet class models disconnected data set
(cid:1) Disconnected data models in-memory cache of data
(cid:2) has collection property of DataTable objects
(cid:2) tables, relations, rows, columns etc.
(cid:2) disconnected and independent of data source.
(cid:1) DataTable is in-memory model of a table
(cid:2) has rows, columns, etc.
DataSet
Customer Name Customer Id
public class DataSet // ...
{
Tables
Ann
0
Bob
1
// tables in DataSet
public System.Data.DataTableCollection Tables { get; }
// ...
}
Customer Id Balance
Rating
public class DataTable // ...
{
0
5000
2
Rows { get;}
1
750
5
// rows and columns currently in DataTable
public System.Data.DataRowCollection
public System.Data.DataColumnCollection Columns{ get;}
// ...
}
.NET Programming - Nguyễn Đạt Thông 429 .NET Programming - Nguyễn Đạt Thông 430
DataRow & DataColumn
Phát sinh DataSet
(cid:1) DataRow is in-memory model of row inside DataTable
(cid:1) Two main ways to create DataSet
(cid:2) several ways to access column data
(cid:2) rows are generated by tables, not created directly
(cid:2) fill from existing data source such as database
○ use DataAdapter and its Fill() method
(cid:2) manually define structure and fill with data
(cid:1) DataColumn models column of DataTable
string text = "select * from authors";
System.Data.SqlClient.SqlConnection conn;
// ...
(cid:2) specify name and data type when creating
// create adapter
System.Data.SqlClient.SqlDataAdapter adapter =
public class DataRow // ...
{
new System.Data.SqlClient.SqlDataAdapter(text, conn);
// create DataSet
System.Data.DataSet authors = new System.Data.DataSet();
public object this[string colName] { get; set;}
public object this[int colIndex] { get; set;}
public object[] ItemArray { get; set;}
// ...
// use adapter to fill DataSet
adapter.Fill(authors);
}
public class DataColumn // ...
{
public DataColumn(string name, Type type);
// ...
}
.NET Programming - Nguyễn Đạt Thông 431 .NET Programming - Nguyễn Đạt Thông 432
108
2/19/2014
Duyệt DataSet
Tự tạo một DataSet
(cid:1) DataSet three levels of data inside
(cid:1) Manually create DataSet
(cid:2) create DataSet object
(cid:2) create tables and add to set
(cid:2) set of contained tables
(cid:2) rows in each table
(cid:2) column values in each row
(cid:1) Manually create DataTable
// traverse DataSet
foreach(System.Data.DataTable table in authors.Tables) {
foreach (System.Data.DataRow row in table.Rows) {
foreach (object data in row.ItemArray) {
// process column value
}
}
}
(cid:2) define table structure
(cid:2) create rows, add rows to tables, fill with data
// create a table and define its columns
System.Data.DataTable customers = new System.Data.DataTable("Customers");
customers.Columns.Add("Name", typeof(string));
customers.Columns.Add("Id", typeof(Int32));
// create a row and add to table
System.Data.DataRow row = customers.NewRow();
row[0] = "Ann";
row[1] = 0;
customers.Rows.Add(row);
// create DataSet and add table to set
System.Data.DataSet data = new System.Data.DataSet();
data.Tables.Add(customers);
.NET Programming - Nguyễn Đạt Thông 433 .NET Programming - Nguyễn Đạt Thông 434
Cập nhật cơ sở dữ liệu
Độc lập với các hệ cơ sở dữ liệu
(cid:1) Update database after changing DataSet
IDbConnection
IDbCommand
IDataReader
IDbDataAdapter
(cid:2) use SqlCommandBuilder to create needed SQL commands
(cid:2) use Update method of DataAdapter to send changes
SqlConnection
SqlCommand
SqlDataReader
SqlDataAdapter
System.Data.SqlClient
string text = "select * from authors";
System.Data.SqlClient.SqlConnection conn;
// ...
// create adapter
System.Data.SqlClient.SqlDataAdapter adapter =
new System.Data.SqlClient.SqlDataAdapter(text, conn);
// create DataSet
System.Data.DataSet authors = new System.Data.DataSet();
OracleConnection
OracleCommand
OracleDataReader
OracleDataAdapter
// use adapter to fill DataSet
adapter.Fill(authors, "authors");
System.Data.OracleClient
// modify DataSet
authors.Tables[0].Rows[4][2] = "Bob";
MySqlDataAdapter
MySqlConnection
MySqlCommand
MySqlDataReader
// attach builder
System.Data.SqlClient.SqlCommandBuilder b =
MySql.Data.MySqlClient
new System.Data.SqlClient.SqlCommandBuilder(adapter);
// update database
adapter.Update(authors, "authors");
.NET Programming - Nguyễn Đạt Thông 435 .NET Programming - Nguyễn Đạt Thông 436
109
2/19/2014
Tóm lược
Tham khảo thêm
(cid:1) How to connect to database using connection?
(cid:1) Introduction to ADO.NET
http://csharp-station.com/Tutorial/AdoDotNet/Lesson01
(cid:1) How to execute a SQL query?
(cid:1) Reading Data with the SqlDataReader
http://csharp-station.com/Tutorial/AdoDotNet/Lesson04
(cid:1) How to fetch data from Database?
(cid:1) Working with Disconnected Data
(cid:1) How to update data to Database?
http://csharp-station.com/Tutorial/AdoDotNet/Lesson05
(cid:1) How to use independent coding of ADO .NET?
(cid:1) Using Stored Procedures
http://csharp-station.com/Tutorial/AdoDotNet/Lesson07
.NET Programming - Nguyễn Đạt Thông 437 .NET Programming - Nguyễn Đạt Thông 438
Tham khảo thêm
Ghi chú
(cid:1) System.Data.OracleClient Namespace
http://msdn.microsoft.com/en-us/library/347d2380(v=vs.90).aspx
(cid:1) MySQL Connector/Net
http://dev.mysql.com/doc/refman/5.5/en/connector-net.html
(cid:1) Connect C# to MySQL
http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL
(cid:1) Connection strings for SQL Server
http://www.connectionstrings.com/sql-server-2012
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
.NET Programming - Nguyễn Đạt Thông 439 .NET Programming - Nguyễn Đạt Thông 440
110