如何为现有方法分配新操作?

Ben*_*Ben 2 .net c# methods class instance

我在 C# 中创建了一个类,它使用“Action”方法。

public void Action()
{

}
Run Code Online (Sandbox Code Playgroud)

该方法是空的,因为当创建该类的新实例时,用户应该能够定义该方法的用途。一个用户可能需要该方法写入控制台,另一个用户可能希望它为变量分配一个值,等等。我有什么办法可以改变该方法在其原始定义之外可以执行的操作,沿着下列的:

//Using the instance "MyClass1", I have assigned a new action to it (Writing to the console)
//Now the method will write to the console when it is called
MyClass1.Action() = (Console.WriteLine("Action"));
Run Code Online (Sandbox Code Playgroud)

Yuv*_*kov 5

有什么方法可以让我改变该方法在其原始定义之外可以执行的操作

不是通过“命名方法”以及您在示例中使用它们的方式。如果您希望您的类能够调用用户定义的执行单元,您需要查看继承层次结构(如 @CodeCaster 答案中通过虚拟方法并覆盖它们指定的那样),或者可能查看delegate

您可以使用Action委托:

public Action Action { get; set; }
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

var class = new Class();
class.Action = () => { /*Code*/ }
Run Code Online (Sandbox Code Playgroud)

并且,当您想调用它时:

if (class.Action != null)
{
   class.Action();
}
Run Code Online (Sandbox Code Playgroud)