Is it possible to overload the ShowDialog method for forms and return a different result?(是否可以重载表单的 ShowDialog 方法并返回不同的结果?)
问题描述
这种方法实际上效果很好,我问了它,然后找到了解决方案.我在重载的 ShowDialog() 方法中添加了正确的调用(它不是完全重载,甚至不是覆盖,但它的工作原理相同.我的新问题是底部的问题.
我有一个表单,您可以在其中单击三个按钮之一.我为返回的结果定义了一个枚举.我想打电话:
I have a form in which you click one of three buttons. I have defined an enum for the returned results. I want to make the call:
MyFormResults res = MyForm.ShowDialog();
我可以用这段代码添加一个新的 ShowDialog 方法:
I can add a new ShowDialog method with this code:
public new MyFormResults ShowDialog()
{
//Show modal dialog
base.ShowDialog(); //This works and somehow I missed this
return myResult; //Form level variable (read on)
}
我为单击按钮时的结果设置了一个表单级变量:
I set a form-level variable for the result when the buttons are clicked:
MyFormResults myResult;
private void btn1_click(object sender, EventArgs e)
{
myResult = MyFormsResults.Result1;
this.DialogResult = DialogResult.OK; //Do I need this for the original ShowDialog() call?
this.Close(); //Should I close the dialog here or in my new ShowDialog() function?
}
//Same as above for the other results
我唯一缺少的是显示对话框(模式)然后返回结果的代码.没有base.ShowDialog()函数,我该怎么做呢?
The only thing I'm missing is the code to show the dialog (modal) and then return my result. There is no base.ShowDialog() function, so how do I do this?
有一个base.ShowDialog()",它可以工作.这是我的新问题:
另外,这是做这一切的最佳方式吗?为什么?
Also, is this the best way to do all this and Why?
谢谢.
推荐答案
更改 ShowDialog() 的功能可能不是一个好主意,人们希望它返回一个 DialogResult 并显示表单,我建议如下我的建议.因此,仍然允许 ShowDialog() 以正常方式使用.
It's proberly not a good idea to change the functionality of ShowDialog(), people expect it to return a DialogResult and show the form, I suggest something like my suggestion below. Thus, still allowing ShowDialog() to be used the normal manner.
您可以在 MyForm 上创建一个静态方法,例如 DoShowGetResult()
You could create a static method on your MyForm, something like DoShowGetResult()
看起来像这样
public static MyResultsForm DoShowGetResult()
{
var f = new MyForm();
if(f.ShowDialog() == DialogResult.OK)
{
return f.Result; // public property on your form of the result selected
}
return null;
}
那你就可以用这个了
MyFormsResult result = MyForm.DoShowGetResult();
这篇关于是否可以重载表单的 ShowDialog 方法并返回不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以重载表单的 ShowDialog 方法并返回不同的结果?
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 如果条件可以为空 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
