我在 C# 中创建了一个类,它使用方法“Action”。
public void Action()
{
}
该方法是空的,因为当创建该类的新实例时,用户应该能够定义该方法的作用。一个用户可能需要该方法来写入控制台,另一个用户可能希望它为变量赋值,等等。我有什么办法可以改变该方法在其原始定义之外可以做的事情,沿着以下:
//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"));
最佳答案
Is there any way for me to change what the method can do outside of its original definition
不是通过“命名方法”以及您在示例中使用它们的方式。如果您希望您的类能够调用用户定义的执行单元,您需要查看继承层次结构(如@CodeCaster 回答中指定的通过虚拟方法并覆盖它们),或者查看 delegates .
您可以使用 Action
代表:
public Action Action { get; set; }
像这样使用它:
var class = new Class();
class.Action = () => { /*Code*/ }
并且,当你想调用它时:
if (class.Action != null)
{
class.Action();
}
关于c# - 如何将新操作分配给现有方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28295858/