要编写一个函数,可以接受 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
类型的值。