要编写一个函数,可以接受 Action
以下是一个示例代码:
public class MyClass
{
public Action MyAction { get; set; }
public void DoSomething(T value)
{
MyAction?.Invoke(value);
}
}
在上面的示例中,我们定义了一个名为MyAction的属性,它可以接受一个泛型参数 T 的 Action。然后,我们在DoSomething方法中使用MyAction属性来执行传递给DoSomething方法的值。
使用示例:
public static void Main(string[] args)
{
MyClass myClass = new MyClass();
// 设置 MyAction 属性为接受 string 类型的 Action
myClass.MyAction = (str) =>
{
Console.WriteLine($"Hello, {str}!");
};
// 调用 DoSomething 方法,并传递一个 string 类型的值
myClass.DoSomething("John");
// 设置 MyAction 属性为接受 int 类型的 Action
myClass.MyAction = (num) =>
{
Console.WriteLine($"The square of {num} is {num * num}.");
};
// 调用 DoSomething 方法,并传递一个 int 类型的值
myClass.DoSomething(5);
}
输出结果:
Hello, John!
The square of 5 is 25.
在上面的示例中,我们先设置MyAction属性为接受string类型的Action,然后调用DoSomething方法传递一个string类型的值。接下来,我们将MyAction属性设置为接受int类型的Action,然后再次调用DoSomething方法传递一个int类型的值。