Reputation: 105
I want to define a property (named FormAbout
) in a class, so that someone using this object could assign a derived type of IFormAbout
. To do this, I have an interface and an implementation of it:
public interface IFormAbout : IDisposable
{
void ShowAbout();
}
public partial class MyFormAbout : Form, IFormAbout
{
public void ShowAbout()
{
base.ShowDialog();
// ...
}
// ...
}
Here, the main Form
with the property I'd like to define:
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();
// ...
}
}
}
The property would be set somehow like this:
formMain1.FormAbout = typeof(MyFormAbout);
Is it possible to do? Thanks in advance.
Upvotes: 1
Views: 69
Reputation: 105
Finally I've found a good solution to my question, and I want to share it with you all.
It is possible to set an explicit implementation of IFormAbout
without instantiate it, by declaring my class FormMain
as generic:
public partial class FormMain<About> : Form where About : IFormAbout
{
private void SomeMethod()
{
using (About frm = Activator.CreateInstance<About>())
{
frm.ShowAbout();
// ...
}
// ...
}
}
Then, we just have to declare an instance of FormMain
like this:
FormMain<MyFormAbout> frm = new FormMain<MyFormAbout>();
Good enough for my purposes.
Upvotes: 0
Reputation: 37000
although you could have a property of type Type
, that´s not what you want here. You just want to assign a new instance of MyFormAbout
to the property, don´t you? So the type of the property becomes IFormAbout
:
public partial class FormMain : Form
{
public IFormAbout FormAbout { get; set; }
private void SomeMethod()
{
FormAbout.ShowAbout();
// ...
}
}
Now you do not need to assign a type, but a concrete instance of it:
FormMain1.AboutForm = new MyAboutForm();
formMain1.SomeMethod(); // this will use the aboutForm from above
Upvotes: 2