, 說我有這樣的代碼在回調中作爲引用傳遞的C#整數?
public void DoSth(Action<QueryTextureResult> result, IEnumerable<string> arr)
{
int totalData = 0;
foreach (var element in arr) // let's say arr.Count() is 10
{
Action<Texture> onImageReceived = (texture) =>
{
if (result != null)
{
var res = new QueryTextureResult()
{
Texture = texture,
QueryId = queryId,
Index = totalData // why this one is always 10 if the callback takes time?
};
result(res);
Debug.Log("INdex: " + res.Index);
}
};
imageManager.GetImage("http://image.url", onImageReceived);
totalData++;
}
}
寫在註釋,如果我有10個元素,是需要時間的result
被調用,爲什麼我收到的QueryTextureResult.Index
永遠是10?它是否通過引用傳遞?有任何解決這個問題的方法嗎?
變量被捕獲,它們都共享相同的內存地址。 –