NEWS

[C#] Hướng dẫn truyền Method vào parametter của function winform

[C#] Hướng dẫn truyền Method vào parametter của function winform
Đăng bởi: Thảo Meo - Lượt xem: 3679 10:27:10, 15/07/2021DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẽ tiếp tục hướng dẫn các bạn cách truyền Method vào parametter ở hàm Function trong lập trình c#, winform.

[C#] Pass a Method as a Parameter in Winform

add_form_to_panel_thumb

Để truyền method vào parameter trong hàm của Winform C#, chúng ta có hai cách:

Cách 1: Sử dụng Func

Cách 2: Sử dụng Action

1. Sử dụng Func để truyền method

Cú pháp:

public delegate returnType Func<in inputType, out returnType>(InputType arg);

input type: là giá trị truyền vào của phương thức method

output type: là giá trị trả về

Các bạn tham khảo đoạn code mẫu dưới đây:

public class MethodasParameter
{
    public int Method1(string input)
    {
        return 0;
    }

    public int Method2(string input)
    {
        return 1;
    }

    public bool RunMethod(Func<string, int> MethodName)
    {
        int i = MethodName("This is a string");
        return true;
    }

    public bool Test()
    {
        return RunMethod(Method1);
    }
}

2. Sử dụng Action để truyền Method vào Parametter

Cú pháp:

public delegate void Action<in T>(T obj);

Code sử dụng Action:

public class MethodasParameter
{
    public int Method1(string input)
    {
        return 0;
    }

    public int Method2(string input)
    {
        return 1;
    }

    public bool RunTheMethod(Action myMethodName)
 {
      myMethodName();
      return true;
 }
  RunTheMethod(() => Method1("MyString1"));
}

Rất đơn giản phải không các bạn.

Thanks for watching!

 

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn truyền Method vào parametter của function winform
Đăng bởi: Thảo Meo - Lượt xem: 3679 10:27:10, 15/07/2021DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.