C# 如何定义以类型作为值的属性
我想在类中定义一个属性(名为C# 如何定义以类型作为值的属性,c#,winforms,properties,C#,Winforms,Properties,我想在类中定义一个属性(名为FormAbout),以便使用此对象的人可以指定ifformabout的派生类型。为此,我有一个接口及其实现: public interface IFormAbout : IDisposable { void ShowAbout(); } public partial class MyFormAbout : Form, IFormAbout { public void ShowAbout() { base.ShowDialog
FormAbout
),以便使用此对象的人可以指定ifformabout
的派生类型。为此,我有一个接口及其实现:
public interface IFormAbout : IDisposable
{
void ShowAbout();
}
public partial class MyFormAbout : Form, IFormAbout
{
public void ShowAbout()
{
base.ShowDialog();
// ...
}
// ...
}
在这里,主表单
和我要定义的属性:
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();
// ...
}
}
}
有可能吗?提前感谢。尽管您可以拥有
类型的属性,但这不是您想要的。您只想将MyFormAbout
的新实例分配给属性,是吗?因此属性的类型变为ifformabout
:
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
最后,我找到了一个很好的解决方案,我想和大家分享。
通过将我的类FormMain
声明为泛型,可以设置ifformabout
的显式实现,而无需实例化它:
public partial class FormMain<About> : Form where About : IFormAbout
{
private void SomeMethod()
{
using (About frm = Activator.CreateInstance<About>())
{
frm.ShowAbout();
// ...
}
// ...
}
}
对我来说已经足够好了。虽然您可以拥有类型为类型的属性,但这不是您想要的。您只想将MyFormAbout
的新实例分配给属性,是吗?因此类似于formMain1.FormAbout=new MyFormAbout()
^^^的内容使得属性的类型仅为ifformabout
为什么不定义为public ifformabout FormAbout{get;set;}
?
public partial class FormMain<About> : Form where About : IFormAbout
{
private void SomeMethod()
{
using (About frm = Activator.CreateInstance<About>())
{
frm.ShowAbout();
// ...
}
// ...
}
}
FormMain<MyFormAbout> frm = new FormMain<MyFormAbout>();