C# quiz – 我错在哪儿?
在开发的时候我遇到了一个迷惑的问题,现在把问题简化一下放在这里。在开始之前,先介绍一下代码的用意 :文中示例及代码完全是为了简化说明问题而造的一个例子,本身没有什么实际意义,因此不必过分追究它的合理性。
首先有一个MyObject的简单类,它有一个Name的属性;然后有一个Operation的类,它可以执行一个Action。我在主函数内创建了一个MyObject的List, 然后有循环它去生成一个Operation的List。 程序期望的结果是循环所有的Operation并执行它,应该打印每一个MyObject的Name。程序如下:
//Example object.
public class MyObject
{
public string Name { get; private set; }
public MyObject(string name)
{
Name = name;
}
}
//An operation class that can be executed.
public class Operation
{
private Action _action;
//Requires an action
public Operation(Action action)
{
_action = action;
}
public void Execute() //Executes the action
{
_action();
}
}
public static void Main(String[] args)
{
// Instantiates a list of my objects.
List<MyObject> myObjects = new List<MyObject>
{
new MyObject("My object 1"),
new MyObject("My object 2"),
new MyObject("My object 3")
};
List<Operation> operators = new List<Operation>();
//Loops all the objects and creates operations.
foreach (var myObject in myObjects)
{
//Instantiates an operation that printing my object's name.
Action action = () => { Console.WriteLine(myObject.Name); };
operators.Add(new Operation(action));
}
//Executes all the operations.
foreach (var operation in operators)
{
operation.Execute();
}
}
public class MyObject
{
public string Name { get; private set; }
public MyObject(string name)
{
Name = name;
}
}
//An operation class that can be executed.
public class Operation
{
private Action _action;
//Requires an action
public Operation(Action action)
{
_action = action;
}
public void Execute() //Executes the action
{
_action();
}
}
public static void Main(String[] args)
{
// Instantiates a list of my objects.
List<MyObject> myObjects = new List<MyObject>
{
new MyObject("My object 1"),
new MyObject("My object 2"),
new MyObject("My object 3")
};
List<Operation> operators = new List<Operation>();
//Loops all the objects and creates operations.
foreach (var myObject in myObjects)
{
//Instantiates an operation that printing my object's name.
Action action = () => { Console.WriteLine(myObject.Name); };
operators.Add(new Operation(action));
}
//Executes all the operations.
foreach (var operation in operators)
{
operation.Execute();
}
}
运行,程序的结果显示如下:
显然不是期望的结果。那么程序的错误在哪儿呢?