我想以回调方式更改一些文本,但是我对以下代码感到困惑:
List<Item> items = new List<Item>();
Item item = new Item();
item.Value = "CCC";
item.ReturnText = () => { return item.Value + "BBB"; };
items.Add(item);
item = new Item();
item.Value = "DDD";
items.Add(item);
// expected:
// Value: CCC, Text: CCCBBB
// Value: DDD, Text: AAA
// BUT ACTUALLY THE OUTPUT IS
// Value: CCC, Text: DDDBBB
// Value: DDD, Text: AAA
foreach (var i in items)
{
Console.WriteLine(i.ToString());
}
public class Item
{
public Item()
{
ReturnText = null;
}
public string Value { get; set; }
public string Text
{
get
{
if (ReturnText != null) return ReturnText();
return "AAA";
}
set { }
}
public delegate string ReturnTextCallback();
public ReturnTextCallback ReturnText;
public override string ToString()
{
return "Value: " + Value + ", Text: " + Text;
}
}
我的英语不好,所以我希望代码可以显示我想做的事情,请有人可以向我解释为什么会发生这种情况?谢谢大家