在C中,使用++i和之间有什么区别i++,哪些应该在for循环的增量块中使用?
我遇到了一个关于C#的有趣问题.我有如下代码.
List<Func<int>> actions = new List<Func<int>>();
int variable = 0;
while (variable < 5)
{
actions.Add(() => variable * 2);
++ variable;
}
foreach (var act in actions)
{
Console.WriteLine(act.Invoke());
}
Run Code Online (Sandbox Code Playgroud)
我希望它输出0,2,4,6,8.但是,它实际输出5个10.
似乎是由于所有操作都涉及一个捕获的变量.结果,当它们被调用时,它们都具有相同的输出.
有没有办法解决这个限制,让每个动作实例都有自己的捕获变量?
我想实现一些与 类似的东西yield return new WaitUntil(() => Check());,但有一个额外的补充。满足条件后Check(),它应该等待 x 秒检查每一帧条件是否仍然为真。
这是我的实现:
private IEnumerator CheckCor(float waitTime)
{
bool checkFlag = true;
bool checkFlag2;
float whileTime;
while (checkFlag)
{
yield return new WaitUntil(() => Check());
checkFlag2 = true;
whileTime = waitTime;
while (whileTime > 0)
{
if (!Check())
{
checkFlag2 = false;
}
whileTime -= Time.deltaTime;
yield return null;
}
if (checkFlag2)
{
checkFlag = false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
哪里Check()
private bool Check();
Run Code Online (Sandbox Code Playgroud)
我的实现工作得很好,但似乎有点长。
有没有更短的方法来实现相同的行为?
(也使其通用将是一个优点,例如yield …
我有一些按钮,每个按钮代表某个级别,并且想要以编程方式添加侦听器,但不太熟悉 C# 的 lambda 函数(也许是一些闭包的东西?),这就是我现在所做的:
for(int i=0; i<levels.Count; i++){
//omit the making a button snippet
button.GetComponent<Button>().onClick.AddListener(() =>
{
Debug.Log("load Scene");
ApplicationModel.currentLevel = levels[i];
SceneManager.LoadScene("Game");
//Application.LoadLevel("Game");
});
}
Run Code Online (Sandbox Code Playgroud)
但是这条线:
ApplicationModel.currentLevel = levels[i];
Run Code Online (Sandbox Code Playgroud)
levels是一个List<Level>并且ApplicationModel是一个根据这篇文章保存信息的类
,但它不断给出 ArgumentOutOfRangeException:
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List`1[Level].get_Item (Int32 index) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633)
GameLevelManger+<initScrollPanel>c__AnonStorey0.<>m__0 () (at Assets/GameLevelManger.cs:72)
Run Code Online (Sandbox Code Playgroud) I've got problem with UI listener. I try to assign click listener to the method in for loop for UI, but every time I've got last option selected.
public Button[] options;
void Start ()
{
for(int i = 0; i < options.Length; i++)
{
options[i].onClick.AddListener(()=> {OptionPressed(i);});
}
}
private void OptionPressed(int i)
{
print (i);
}
Run Code Online (Sandbox Code Playgroud)
It's always print 3. My question is why? and also why 3 while there is only 3 buttons, so it should be 2?