Chuyển đến nội dung chính

Bài đăng

Đang hiển thị bài đăng từ Tháng 1, 2011

Chuyển từ Anonymous Function sang Lambda

Giả sử bạn có hàm cộng 2 số a và b và hiển thị kết quả lên màn hình. Bạn dùng hàm Calc để tính kết quả. Nếu bạn chỉ tính có 1 lần và không sử dụng lại nữa, bạn có thể sử dụng delegate Function. delegate R BinOp<a,b,r>(A a, B b); int Calc(BinOp<int, int, int> f, int a, int b) { return f(a, b) } Hàm Calc int result = Calc( delegate (int a, int b) { return a + b; } , 1, 2); Nếu chuyển qua biểu thức Lambda: int resultInLamBda = Calc((a, b) => a + b, 1, 2);

Delegate trong C# (Phần 1)

Delegate là khái niệm trong C#, nó giống như con trỏ hàm của C++. Delegate là con trỏ trỏ vào các hàm có cùng đối(số lượng đối và kiểu đối giống nhau). Late Binding Delegates: A delegate is a repository of type-safe function pointers. Ví dụ: Khai báo Lớp Hello class Hello { public static void ChaoBan() { Console.WriteLine("Chao ca nha"); } public static void ChaoBan(string s) { Console.WriteLine("Chào {0}",s); } } Khai báo Hàm Delegate public delegate void Write(); public delegate void WriteS(string s); Cách sử dụng hàm Deleagate: var myDelegate = new MyClassWithDelegate.Write(Hello.ChaoBan); var myDelegateS = new MyClassWithDelegate.WriteS(Hello.ChaoBan); myDelegate(); myDelegateS("Ban No");//Nếu bạn không truyền tham số sẽ báo lỗi Lưu ý: Bạn có thể dùng hàm Invoke trong delegate myDelegateS.Invoke("Bạn T"); Còn ý nghĩa của nó thế nào thì mình không biết. (

Delegate Function

Hàm Delegate không cần khai báo tên hàm và không được lưu vào bộ nhớ khi biên dịch public delegate void Add(out int numOne,out int numTwo); public delegate int Sub(int numOne,int numTwo); class Maths { static void Start() { int valOne; int valTwo; Add objAddition = delegate(out int numOne,out int numTwo) { numOne = 10; numTwo = 20; int result = numOne + numTwo; Console.WriteLine("Result of Addition : {0}",result); }; objAddition(out valOne,out valTwo); Console.WriteLine("valOne={0},valTwo={1}",valOne,valTwo); Sub objSub = delegate(int numOne, int numTwo) { return numOne - numTwo; }; Console.WriteLine("result={0}",objSub(valOne,valTwo)); } static void Main(string[] args) { Start();