我一直在努力了解事件/代表,但我对两者之间的关系感到困惑.我知道委托允许您调用不同的函数,而无需知道调用的是什么特定函数.(例如:图形函数需要接受要绘制的不同函数的输入).
但我没有看到代表如何在事件中使用.
有人可以构建一个简单的示例(伪代码或C#或Java),说明代理与事件相关的工作方式吗?
谢谢!
我正在尝试用 Java 制作自定义事件和侦听器。我已经看过这些文章和问题:
https://www.javaworld.com/article/2077333/core-java/mr-happy-object-teaches-custom-events.html
但我仍然无法真正理解它。这就是我想要做的:
我有一个String对象,其内容随着程序运行而变化。我希望能够向字符串添加一个侦听器,该侦听器侦听它是否包含特定字符串以及何时运行一段代码。我想像这样使用它:
String string = "";
//String.addListener() and textListener need to be created
string.addListener(new textListener("hello world") {
@Override
public void onMatch(
System.out.println("Hello world detected");
)
}
//do a bunch of stuff
string = "The text Hello World is used by programmers a lot"; //the string contains "Hello World", so the listener will now print out "Hello world detected"
Run Code Online (Sandbox Code Playgroud)
我知道可能有更简单的方法来做到这一点,但我想知道如何做到这一点。
谢谢@Marcos Vasconcelos 指出您不能向String对象添加方法,那么有没有办法使用@Ben 指出的自定义类?