gpt4 book ai didi

c# - 将表单列表存储在数组中

转载 作者:太空宇宙 更新时间:2023-11-03 11:41:19 25 4
gpt4 key购买 nike

我有一个程序需要按给定顺序浏览一系列屏幕。我想做的是集中管理它,使用类似于类工厂的东西,我在其中发送对下一个表单的请求,它实例化并返回下一个表单。然而,我有以下内容,这将立即实例化所有表单:

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;
}

(这不会编译)

最佳答案

一种方法是将类型存储在列表中并使用 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;
}

关于c# - 将表单列表存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4711701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com