C#中有没有一种方法可以像jQuery的"one"中那样一次调用方法?方法? [英] Is there a way in C# to call a method just once like in the jQuery "one" method?
本文介绍了C#中有没有一种方法可以像jQuery的"one"中那样一次调用方法?方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有一种方法可以在C#中仅执行一次代码,例如jquery中的一个":
I wish to know if there is a way to execute code in C# just once, like "one" in jquery:
$(#foo").one("click",function(){alert(这将只显示一次.");});
$("#foo").one("click", function() { alert("This will be displayed only once."); });
我想做的是以下事情:
public void foo(){
Console.Write("hello");
}
然后
foo();
foo();
foo();
并且输出结果必须为
hello
我正在寻找一个库,而不仅仅是使用flags属性.
I´m looking for a library and not just using flags attributes.
推荐答案
我无法想象为什么要这样做,但是如果您确实做到了,并且希望将其通用化,那么您可以这样做:
I can't imagine why do something like that, but if you really do it and if you want it universal for any method, you can do this:
void Main() {
var myFoo = callOnlyOnce(foo);
myFoo();
myFoo();
myFoo();
var myBar = callOnlyOnce(bar);
myBar();
myBar();
myBar();
}
void foo(){
Console.Write("hello");
}
void bar() { Console.Write("world"); }
Action callOnlyOnce(Action action){
var context = new ContextCallOnlyOnce();
Action ret = ()=>{
if(false == context.AlreadyCalled){
action();
context.AlreadyCalled = true;
}
};
return ret;
}
class ContextCallOnlyOnce{
public bool AlreadyCalled;
}
这篇关于C#中有没有一种方法可以像jQuery的"one"中那样一次调用方法?方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文