gpt4 book ai didi

c# - 如何将新操作分配给现有方法?

转载 作者:太空宇宙 更新时间:2023-11-03 18:28:24 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com