Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Chương 7:

Others
Nguyễn Mạnh Tuấn
tuannm@ueh.edu.vn
Nội dung
 Generic
 Default value
 Delegate
 Anonymous Type
 Lambda expressions
 Difference between Enumerable, Collection & List

2
Generic <T>
public void Swap<T>(ref T a, ref T b)
{
T tmp = a; a = b; b = tmp;
}

private void tbnN_Click(object sender, EventArgs private void btnS_Click(object sender, EventArgs e)
e) {
{ string s1 = txtS1.Text;
double n1 = int.Parse(txtN1.Text); string s2 = txtS2.Text;
double n2 = int.Parse(txtN2.Text); Swap<string>(ref s1, ref s2);
Swap(ref n1, ref n2); txtS1.Text = s1;
txtN1.Text = n1.ToString(); txtS2.Text = s2;
txtN2.Text = n2.ToString(); }
}

public class Lop<A>


{
A MaLop { get; set; }
string TenLop { get; set; }
}

3
new object, collection, list… and new object
without Constructor
• We can new object, collection, list with initial values
Student stu = new Student { Name = “Quân", Age = 20 };
List<string> list = new List<string> { "Phát" , "Đạt", "Nga", "Minh" };

• Anonymous Type for an Object - an Object without class  export to XML, JSON…
var noClassObj = new { FirstName = “Tung", LastName = “Le"};
Console.WriteLine(noClassObj. FirstName + noClassObj. LastName);

• New Object without Constructor


List<Student> listStu = new List<Student>()
{ new Student { MSSV = "1" }, new Student { MSSV = "2", HoTen = "Tung 2" } };

public void AddStudentWithoutConstructor(string pMSSV, string pHoTen, double pDTB)


{
Student student = new Student() { MSSV = pMSSV, HoTen = pHoTen, DTB = pDTB };
listStu.Add(student);
}

4
Optional Parameters

private string AddOptionalParameters(int n1, int n2, int n3 = 10, string s = "Optional
default")
{
return n1.ToString() + " - " + n2.ToString() + " - " + n3.ToString() + " - " + s;
}

5
Extension Method for Class
public class Student
{
public string HoTen { get; set; }
List<int> intList = new List<int> { 1, 5, 7 };
public string MSSV { get; set; } List<string> stringList = new List<string> {
internal double DTB { get; set; } "Tung", "Tuan", "Trung" };
//auto-property: p r i v a t e f i e l d , g e t t e r & s e t t e r b e
a u to g e n e r a te d
}

public static class ClassExtensions


{ Student stu = new Student() { MSSV = "1", HoTen = "Tung",
public static T FirstList<T>(this List<T> list)
DTB = 4.9 };
//Generic và Extension Method
{ richTextBox1.Text += stu.MSSV + " - " + stu.HoTen
return list.First(); + " - " + stu.DTB.ToString() + "\n";
}
public static void CongDiem(this Student stu) stu.CongDiem();
{ richTextBox1.Text += "Sau cộng điểm: " + stu.MSSV + " - "
stu.DTB++; + stu.HoTen + " - " + stu.DTB.ToString() + "\n";
}
public static void TruDiem(this Student stu)
stu.TruDiem();
{
stu.DTB--; richTextBox1.Text += "Sau trừ điểm: " + stu.MSSV + " - " +
} stu.HoTen + " - " + stu.DTB.ToString() + "\n";
}

6
Delegate
 Delegate là một kiểu dữ liệu đặc biệt trong C# được sử
dụng để khai báo tham chiếu tới các hàm hoặc phương
thức (Có thể hiểu là con trỏ trỏ tới hàm)
 Khi gán một hàm hoặc phương thức cho delegate thì
delegate sẽ trỏ tham chiếu tới hàm, phương thức đó.Sau
đó thay vì ta gọi hàm trực tiếp, ta có thể thông qua
delegate để gọi mà không cần biết rõ tên hàm đó
 Delegate giúp cho việc gọi hàm trở nên linh hoạt hơn.
 Có thể thêm bớt các hàm cần thiết cho Delegate như
dựng một kịch bản xử lý linh động.

7
Delegate
 Function pointer
 MultiCast
 Callback (Function Pointer)
public delegate int DelegateCong(int x, int y = 1); //Khai báo Delegate, kết hợp default value

private void GoiDelegate(DelegateTest goiDelegateTest)


{
int kq = goiDelegateTest(10, 10);
}

DelegateTest delegateTest = Cong;


int kq = delegateTest(5, 6);
rtbTest.Text = kq.ToString() + " -- Hết test hàm Cộng đầu tiên" + "\n";
delegateTest += Nhan;
kq = delegateTest(2, 7);
rtbTest.Text = rtbTest.Text + kq.ToString() + " -- Hết test hàm Nhân thứ 2" + "\n";
delegateTest -= Cong;
kq = delegateTest(3, 4);
GoiDelegate(delegateTest);

8
Anonymous
• Anonymous Type for an Object - an Object without class  export to XML, JSON…
var noClassObj = new { FirstName = “Tung", LastName = “Le"};
Console.WriteLine(noClassObj. FirstName + noClassObj. LastName);

• Anonymous Function  needn’t write a real function for Delegate call back
public delegate int DelegateCong(int x, int y = 1); //Khai báo Delegate, kết hợp default value

#region Anonymous Function

DelegateCong delegateCong = delegate (int x, int y) { return x + y; };

richTextBox1.AppendText("\nAnonymous Function: " + delegateCong(5, 9) + " và " + delegateCong(20) + "\n");

#endregion

https://learn.microsoft.com/en-us/dotnet/csharp/language-
reference/operators/lambda-expressions

9
Lambda expressions
• Expression lambda that has an expression as its body:

(input-parameters) => expression

• Statement lambda that has a statement block as its body:

(input-parameters) => { <sequence-of-statements> }

• Any lambda expression can be converted to a delegate type.


• The delegate type to which a lambda expression can be converted is defined by the types
of its parameters and return value.
• If a lambda expression doesn't return a value, it can be converted to one of the Action
delegate types; otherwise, it can be converted to one of the Func delegate types.
• For example, a lambda expression that has two parameters and returns no value can be
converted to an Action<T1, T2> delegate. A lambda expression that has one parameter and
returns a value can be converted to a Func<T, TResult> delegate

https://learn.microsoft.com/en-us/dotnet/csharp/language-
reference/operators/lambda-expressions

10
Lambda expressions - Examples
#region Lambda Expressions - Func
Func<int, int, int> TongLambdaExpression = (x, y) => x + y;
richTextBox1.AppendText("\nLambda Expressions: Func(3, 5) = " + TongLambdaExpression(3, 5) + "\n");

int[] numbers = { 1, 2, 3, 4, 5 };
var NhanDoi = numbers.Select(x => x * 2); //Có dùng Linq - Select
richTextBox1.AppendText("\nLambda Expressions: var = " + string.Join(" ", NhanDoi) + "\n");
#endregion

#region Lambda Expressions – Action (with Statements)


Action<string> chaoBan = a =>
{
string cauChao = "Xin chào bạn " + a;
richTextBox1.AppendText("\nLambda Expressions Action: " + cauChao);
};
chaoBan("Minh");
#endregion

11
Interface

interface IHuman public class Student: IHuman, IPrintHoTen public class GiangVien : IHuman, IPrintHoTen
{ { {
string HoTen { get; set; } public string HoTen { get; set; } public string HoTen { get; set; }
int ThuNhap { get; set; } public int ThuNhap { get; set; } public int ThuNhap { get; set; }
void TangThuNhap(int public string MSSV { get; set; } public string MaGV { get; set; }
x); internal double DTB { get; set; } public string HocHamHocVi { get; set; }
} public void TangThuNhap(int x) => ThuNhap += x
interface IPrintHoTen public string InHoa() public string InHoa()
{ { {
string InHoa(); return HoTen == null? "": return HoTen == null ? "" : HoTen.ToLower();
string InThuong(); HoTen.ToUpper(); }
} }
public string InThuong()
public string InThuong() {
{ return HoTen == null ? "" : HoTen.ToLower();
return HoTen == null ? "" : }
HoTen.ToLower(); }
}

public void TangThuNhap(int x)


{
ThuNhap += 1000 + x;
}
}

12
Interface -

private void btnTestInterface_Click(object sender, EventArgs e)


{
IHuman[] human = new IHuman[2];
human[0] = new Student() { MSSV = "SV1", ThuNhap = 5, HoTen = "Sanh Vien" };
human[1] = new GiangVien() { ThuNhap = 100, MaGV = "G1" };

richTextBox1.AppendText($"\nDemo Interface:\n");
for (int i = 0; i < human.Length; i++)
{
human[i].TangThuNhap(5000);
richTextBox1.AppendText($"{human[i].GetType()} - {human[i].ThuNhap} -
{((IPrintHoTen)human[i]).InHoa()} - {((IPrintHoTen)human[i]).InThuong()}\n");
}
}

13
Difference between Enumerable, Collection &
List

List
Enumerable Collection - allows items to
- unordered - can add/remove have an order
- unmodifiable items (accessing and
removing by index)

14
IEnumerable
It has no order.

You cannot add or remove items from the


set.
You cannot even get a count of items in
the set.
It strictly lets you access each item in the
set, one after the other.

15
ICollection
It is a modifiable set.

You can add and remove objects from the set

You can also get the count of items in the set.

But there still is no order, and because there is no order:


no way to access an item by index, nor is there any way
to sort.

16
IList

It is an ordered set of objects.

You can sort the list

Access items by index, remove


items by index.

17
In fact, when looking at the interfaces for
these, they build on one another

18
Tips - IEnumberable
 When declaring variables, or method parameters, you should choose to
use IEnumerable, ICollection, IList based on what conceptually you need to
do with the set of objects.

 If you just need to be able to do something to every object in a list, then you
only need IEnumerable

 You don't care if the Users are kept in a List<T>, Collection<T>, Array<T>
or anything else. You only need the IEnumerable<T> interface.

19
Tips – IList & ICollection
 If you need to be able to add, remove, or count
the items in a set, then use a Collection

 If you care about a sort order, and need the


order to be correct, then use a List

20
Difference between Enumerable, Collection &
List

21
Demo
 Link code mẫu

22
Game
 Rắn ăn mồi: link
 Có đầy đủ hướng dẫn và video
 Yêu cầu: lưu vết lại trò chơi để khi mở lại thì vẫn giữ
trạng thái cũ
 Game caro 2 người: link
 Có đầy đủ hướng dẫn và video

23
Quản lý
 Keyword search:
 Winform quản lý github
 Chấm công: link
 Entity Framework

 Quản lý quán cafe: link


 Entity Framework

24

You might also like