저는 D를 배우고 있으며 일반적인 유형을 처리하는 방법을 가지고 있습니다. D에서 다양한 입력 인수로 대리자를 저장할 수있는 배열을 어떻게 선언 할 수 있습니까?
이 예제에서는 JavaScript가 .addEventListener / .dispatchEvent를 사용하는 방식을 부분적으로 모방하려고 노력하고 있으며이를 위해 다양한 이벤트 유형을 입력 인수로 가질 리스너 배열을 저장해야합니다. 나는 많은 타입 캐스팅을 앞뒤로 방지하려고 노력하고 있지만 동일한 배열에 저장해야하는 지점에 갇혀 있습니다.
import std.stdio;
class Event {
}
class NewEvent : Event {
}
class EventTarget {
void addEventListener(T)(void delegate(T) listener) {
this.listeners ~ listener;
}
void dispatchEvent(T)(T event) {
foreach (listener; this.listeners) {
writeln("listener: ", listener, " ", event);
// TODO: call listener if it's input argument matches the T type
// if (type is the one matching the listeners first input argument) {
// listener(event);
// }
}
}
private:
// TODO: find a way to store multiple event types in this array
void delegate(T)[] listeners;
}
void main() {
auto target = new EventTarget();
target.addEventListener((NewEvent event) {
write("executed handler for NewEvent", event);
});
target.addEventListener((Event event) {
write("executed handler for Event", event);
});
target.dispatchEvent(new NewEvent());
target.dispatchEvent(new Event());
}
여기에 놀이터가 있습니다 https://run.dlang.io/is/XdTVBc
이것은 작동합니다.
import std.stdio;
import std.traits;
abstract class Event {
}
class NewEvent : Event {
}
class NewEvent2 : Event {
}
class EventTarget {
void addEventListener(T : Event)(void delegate(T) listener) {
this.listeners ~= DG(listener);
}
void dispatchEvent(T : Event)(T event) {
foreach (listener; listeners)
{
if (listener.type_name == fullyQualifiedName!T)
{
listener(event);
}
}
}
private:
DG[] listeners;
}
struct DG
{
string type_name;
void delegate(Event) dg;
alias dg this;
this(T : Event)(void delegate(T) listener)
{
type_name = fullyQualifiedName!T;
dg = cast(void delegate(Event)) listener;
}
}
void main() {
auto target = new EventTarget();
target.addEventListener((NewEvent event) {
writeln("executed handler for NewEvent", event);
});
target.addEventListener((NewEvent2 event) {
writeln("executed handler for Event", event);
});
target.dispatchEvent(new NewEvent());
target.dispatchEvent(new NewEvent2());
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다