我有一个程序需要按给定顺序浏览一系列屏幕。我想要做的是集中管理,使用类似于类工厂的东西,在那里我发送下一个表单的请求,然后实例化并返回下一个表单。我有以下内容,但是,这将立即实例化所有表格:
private List<Form> screens = new List<Form>() { new Form1(), new Form2(), … };
private Form currentForm;
private int currentPos;
public Form Next()
{
currentForm = screens[++currentPos];
return currentForm;
}
有没有办法在实际请求发生之前推迟实例化?例如:
private List<Form> screens = new List<Form>() { Form1,Form2, …};
private Form currentFrm;
private int currentPos;
public Form Next()
{
currentForm = new screens[++currentPos];
return currentFrm;
}
(这不会编译)
答案 0 :(得分:2)
一种方法是在列表中存储类型,并使用Activator.CreateInstance()动态创建表单实例:
private Type[] screenTypes = new Type[] {
typeof(Form1),
typeof(Form2),
...
};
private Form currentForm;
private int currentPos;
public Form Next()
{
currentForm = (Form) Activator.CreateInstance(screenTypes[++currentPos]);
return currentForm;
}
答案 1 :(得分:0)
您可以使用代表列表,例如:
List<Func<Form>> screens = new List<Func<Form>>
{
() => new Form1(),
() => new Form2(),
...
};
答案 2 :(得分:0)
private List<Type> screens = new List<Type>() { typeof(Form1), typeof(Form2), … };
Type t = screens[++currentPos];
return (Form)Activator.CreateInstance(t);
答案 3 :(得分:0)
另一种选择......
public IEnumerable<Form> Forms
{
yield return new Form1();
yield return new Form2();
yield return new Form3();
...
}