【发布时间】:2021-05-16 20:33:33
【问题描述】:
此代码有效:
@page "/"
<button @onclick="@(()=>fun(0))" style="color: @style1[0]">
Click me
</button>
<button @onclick="@(()=>fun(1))" style="color: @style1[1]">
Click me
</button>
<button @onclick="@(()=>fun(2))" style="color: @style1[2]">
Click me
</button>
@code{
List<string> style1 = new List<string> { "black" , "black", "black" };
void fun(int m)
{
try
{
if (style1[m] == "black") style1[m] = "red";
else style1[m] = "black";
}
catch
{
Console.WriteLine("m = {0}", m);
}
}
}
但是这个没有:
@page "/"
@for (int i = 0; i < 3; i++)
{
<button @onclick="@(()=>fun(i))" style="color: @style1[i]">
Click me
</button>
}
@code{
//same as above
}
这是控制台中的错误(没有 try-catch):
未处理的异常呈现组件:索引超出范围。必须是非负数且小于集合的大小。
try-catch 之后:
m = 3
谢谢
【问题讨论】:
-
尝试在
for循环中添加临时变量并在fun()中使用它:var tmp = i;和()=>fun(tmp) -
非常感谢。有效。您能否描述一下这些语句之间的区别以及为什么它不起作用?
-
这就是closures 在 C# 中的工作方式。