我有一个带有事件的类,然后在另一个.cs文件中,我还有一个我订阅该事件的类。但是该事件从未成功触发,并且由于某种原因该事件为null。我在做什么错了?
头等舱
[1] 1 NA 1 1 1 NA 1 NA 1 1
[1] "elf" NA "elf" "elf" "elf" NA "elf" NA "elf" "elf"
事件类:
dat2 <- as.data.frame(dat)
names(dat2) <- new_labels
dat2 <- list(dat2, dat2)
dat2[[1]][dat2[[1]] == 2] <- NA
dat2[[2]][dat2[[2]] == 1] <- NA
w1 <- which(dat2[[1]] == TRUE, arr.ind = TRUE)
w2 <- which(dat2[[2]] == 2, arr.ind = TRUE)
dat2[[1]][w1] <- colnames(dat2[[1]])[w1[,"col"]]
dat2[[2]][w2] <- colnames(dat2[[2]])[w2[,"col"]]
dat2 <- lapply(dat2, function(x) { x[is.na(x)] <- "" ; x})
[[1]]
elf hobbit wizard ranger
1 elf
2 hobbit
3 elf
4 elf
5 elf
6 wizard
7 elf
8 hobbit
9 elf
10 elf
[[2]]
elf hobbit wizard ranger
1 wizard
2 wizard
3 ranger
4 wizard
5 ranger
6 elf
7 wizard
8 ranger
9 ranger
10 ranger
我订阅该活动的班级:
class TestClass
{
public static void CountStart()
{
int CountVal = 0;
do
{
CountVal = CountVal + 1;
if (CountVal % 5 == 0)
{
SimpleEventSender EventSender = new SimpleEventSender();
EventSender.StartEvent();
}
Thread.Sleep(1000);
} while (CountVal < 100);
}
}
我尝试按照“ Notify when event from another class is triggered”中的答案进行操作,但似乎没有效果。
答案 0 :(得分:4)
事件处理程序与该类的实例(在这种情况下为max
)相关联。
您要创建多个SimpleEventSender
实例:
SimpleEventSender
构造函数中的一个,您可以在其中订阅事件Form1
的每5次迭代中一次,您可以在其中引发事件-但是在CountStart
的新实例上,没有任何订阅者您几乎可以肯定要使用SimpleEventSender
的单个实例,例如
SimpleEventSender
答案 1 :(得分:0)
那是因为您要将此函数分配给SimpleEventSender实例的不同事件。
public Form1()
{
SimpleEventSender newevent1 = new SimpleEventSender();
// You are subscribing to the event of this instance
newevent1.NewEvent += new_event;
InitializeComponent();
}
-
public static void CountStart()
{
int CountVal = 0;
do
{
CountVal = CountVal + 1;
if (CountVal % 5 == 0)
{
// But here you are creating another instance of SimpleEventSender so it doesn't have anything subscribed to it
SimpleEventSender EventSender = new SimpleEventSender();
EventSender.StartEvent();
}
Thread.Sleep(1000);
} while (CountVal < 100);
}
换句话说-您正在Form1()构造函数中订阅一个对象,并且从CountStart()函数中完全不同的对象中调用“ StartEvent()”函数。