我想在一个类中定义一个属性(名为FormAbout
),以便使用此对象的人可以分配派生类型IFormAbout
。为此,我有一个接口及其实现:
public interface IFormAbout : IDisposable
{
void ShowAbout();
}
public partial class MyFormAbout : Form, IFormAbout
{
public void ShowAbout()
{
base.ShowDialog();
// ...
}
// ...
}
在这里,主要的Form
具有我要定义的属性:
public partial class FormMain : Form
{
// --- This is what I don't know how to do --- //
public Type<IFormAbout> FormAbout { get; set; }
// ------------------------------------------- //
private void SomeMethod()
{
using (FormAbout frm = new FormAbout())
{
frm.ShowAbout();
// ...
}
}
}
该属性的设置方式如下:
formMain1.FormAbout = typeof(MyFormAbout);
有可能吗?预先感谢。
答案 0 :(得分:2)
尽管您可以具有类型Type
的属性,但这不是您想要的。您只想为属性分配MyFormAbout
的新实例,不是吗?因此,属性的类型变为IFormAbout
:
public partial class FormMain : Form
{
public IFormAbout FormAbout { get; set; }
private void SomeMethod()
{
FormAbout.ShowAbout();
// ...
}
}
现在,您无需分配类型,而需要分配其具体实例:
FormMain1.AboutForm = new MyAboutForm();
formMain1.SomeMethod(); // this will use the aboutForm from above
答案 1 :(得分:0)
最后,我为我的问题找到了一个很好的解决方案,我想与大家分享。
通过将我的类IFormAbout
声明为泛型,可以设置FormMain
的显式实现而无需实例化:
public partial class FormMain<About> : Form where About : IFormAbout
{
private void SomeMethod()
{
using (About frm = Activator.CreateInstance<About>())
{
frm.ShowAbout();
// ...
}
// ...
}
}
然后,我们只需要声明一个FormMain
的实例,像这样:
FormMain<MyFormAbout> frm = new FormMain<MyFormAbout>();
足以满足我的目的。