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

标签 c# .net class methods instance

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

相关文章:

c# - { };是什么以及如何做在 C# 中工作?

c# - 在 Xamarin Master-Detail MVVM 设置中,如何从 subview 的 View 模型中触发事件并让它被父 View 的 View 模型捕获

.net - Cosmos SDK v3 不记录文档创建

.NET Rx Koans : Why does this test case fail?

c# - 保持我的列表/词典在全局范围内可访问

c# - 尝试优化 MongoDB 的 I/O

c# - 如何在 C# 中使用 wkHtmltoPdf 从静态 html 文件生成 PDf 文件

c# - SQL语法错误: Remove/Disclude Apostrophe's?

python - 你能像字符串替换一样快捷地使用Python方法吗?

c++ - 在 C++ 中,如何确保一个对象在另一个对象之前构造?