Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何定义以类型作为值的属性_C#_Winforms_Properties - Fatal编程技术网

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>();