Hàm anonymous trong C# là gì?

{{FormatNumbertoThousand(model.total_like)}} lượt thích
768 lượt xem
C#/.Net middle

Hàm anonymous (hàm ẩn danh) là một câu lệnh hoặc biểu thức "nội tuyến" có thể được sử dụng ở bất cứ nơi nào mong đợi một kiểu delegate. Bạn có thể sử dụng nó để khởi tạo một delegate đã đặt tên hoặc truyền nó làm tham số phương thức.

Có hai loại hàm anonymous:

  • Lambda Expressions (biểu thức Lambda)
  • Anonymous Methods (phương thức ẩn danh)
// Original delegate syntax required
// initialization with a named method.
TestDelegate testDelA = new TestDelegate(M);

// C# 2.0: A delegate can be initialized with
// inline code, called an "anonymous method." This
// method takes a string as an input parameter.
TestDelegate testDelB = delegate(string s) {
   Console.WriteLine(s);
};

// C# 3.0. A delegate can be initialized with
// a lambda expression. The lambda also takes a string
// as an input parameter (x). The type of x is inferred by the compiler.
TestDelegate testDelC = (x) => {
   Console.WriteLine(x);
};

// Invoke the delegates.
testDelA("Hello. My name is M and I write lines.");
testDelB("That's nothing. I'm anonymous and ");
testDelC("I'm a famous author.");
{{login.error}}