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 方法并返回不同的结果?
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
