带有自定义类的C#操作委托
本文关键字:操作 自定义 | 更新日期: 2023-09-27 18:00:22
当我没有显式传递引用方法的输入参数类型时,具有自定义类的Action委托如何工作:
DirectMethodCall.PassMethod(x=>x.NoReturnOneParameterMethod(1));
public static void PassMethod(Action<NewClass> c)
{
NewClass op = new NewClass();
c(op);
}
为什么我需要将"操作"传递给Action代理?
由于注释对于发布代码示例有点混乱,我将在这里继续。
你没有重复代码,你误解了你实际编码的内容。public static void PassMethod(Action<NewClass> c)
表示PassMethod
需要一个在NewClass
对象上执行的方法作为参数。
也许这会让事情变得更清楚:
void Main()
{
//I am defining the implementation of a method which requires as integer as a parameter, but I don't actually invoke it, just define it.
ExecuteMethod(i => Console.WriteLine(i));
}
public static void ExecuteMethod(Action<int> method)
{
//I don't know what method does, all I know is that I am running it with the number 5.
method(5);
}
ExecuteMethod
采用一个需要整数的方法。它不知道这个方法的作用。它只知道它需要一个int,并将值5
传递给它
实际代码来自调用者:
i => Console.WriteLine(i)
这里,i
被设置为5,因此结果是5被打印到控制台。
您的PassMethod
需要一个接受一个类型为NewClass
的参数的委托,它使用参数1
调用NoReturnOneParameterMethod()
,并且返回类型为void
Action<T>
表示它是一个以类型T
为参数的委托,返回类型为void
。
请参阅:MSDN Action