是否有任何简单的算法可以在方法中第一次运行(例如在本例中我们称之为example())
private bool trigger
private int timer=0;
public void main()
{
for (int i =0;i<5;i++){
if (trigger==false)
Console.WriteLine("loading...");
else
Console.WriteLine("hello world");
example()
}
}
public void example()
{
if (timer==0)
{
//my loading data , like define value to variable or any thing else
trigger = true ; // define a example variable trigger;
}
else
{
// after loading data do it at runtime
trigger = false ;
}
timer++;
}
答案 0 :(得分:1)
在类
中使用静态变量public class trigger
{
static bool isTriggered = false;
static int timer = 0;
public static void main()
{//not a console app-- main used cause op used it
if (timer==0) isTriggered=true;
else istriggered=false;
timer++;//happens no matter what
}
}
这可能对事件有意义......试试吧!
public class trigger
{
static int timer = 0;
//events
public static event EventHandler<TriggerEventArgs> Trigger;
static void onTrigger(object sender, TriggerEventArgs e){if(Trigger != null)Trigger(sender,e);}
public static void main()// <--- no args?
{//not a console app-- main used cause op used it
if (timer==0)onTrigger(new object(),new TriggerEventArgs(/*stuff could go here*/));
/*
else
istriggered=false;
*/
timer++;//happens no matter what
//increment your life away
}
}
public class TriggerEventArgs : EventArgs
{
//what ever you could possibly need and more
//TODO: add constructor so /*stuff can go here*/
}
然后在项目中使用初始化函数,如
void initializefunc()
{
trigger.Trigger += subscription;
}
void subscription(object sender, TriggerEventArgs e)
{
//meaningful code
}
或者我认为你可以重载++运算符(完整代码示例)
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{//the real console app
//test the strange trigger class
trigger.Trigger += trigger_Trigger;
trigger t = new trigger();
trigger a = new trigger();
for (int x = 0; x <= 9; x++)
{
t++;
a++;
}
Console.ReadLine();
}
static void trigger_Trigger(object sender, TriggerEventArgs e)
{
Console.WriteLine("once");
}
}
public class trigger
{
static int timer = 0;
//standard event pattern (static style)
public static event EventHandler<TriggerEventArgs> Trigger;
static void onTrigger(object sender, TriggerEventArgs e) { if (Trigger != null)Trigger (sender, e); }
//overload the ++ operator
public static trigger operator ++ (trigger t)
{
trigger.ops_main();//yeah.. i know this is kinda strange
//but so is the question
return t;
}
public static void ops_main()// <--- no args?
{//not a console app-- main used cause op used it
if (timer == 0) onTrigger(new object(), new TriggerEventArgs());
/*
else
istriggered=false;
*/
timer++;//happens no matter what
//increment your life away
}
}
public class TriggerEventArgs : EventArgs
{
//what ever you could possibly need and more
}
}
答案 1 :(得分:0)
你正在做什么似乎有点奇怪,但简单的答案是将你的0和1改为真和假
private bool trigger
private int timer;
public void main()
{
if (timer==0)
trigger=true;
else
trigger=false;
timer++;
}