【问题标题】:Generic class call that have parameters具有参数的通用类调用
【发布时间】:2016-10-27 16:27:38
【问题描述】:

在我的form1中我有这个方法。

public void ChangeView<T>() where T : Control, new()
    {
        if (transitionManager1.IsTransition)
        {
            transitionManager1.EndTransition();
        }

        transitionManager1.StartTransition(BasePanel);
        try
        {

            T find = Find<T>(BasePanel);
            if (find != null)
            {
                find.BringToFront();
            }
            else
            {
                find = new T();
                find.Parent = BasePanel;
                find.Dock = DockStyle.Fill;
                find.BringToFront();
            }

        }
        finally
        {
            transitionManager1.EndTransition();
        }
    }

问题是当我试图从名为 userC1 的用户控件调用此方法时,该控件在构造函数中有一些参数,如下所示

Form1 f;
    public UserC1(Form1 f)   
    {
        InitializeComponent();
        this.f = f;
    }

我在表格1中调用方法如下

ChangeView<UserC1>(); 

但上面的代码是一个错误它说 必须是具有无公共参数构造函数的非抽象类型,才能将其用作泛型类型或方法中的参数。

我怎样才能摆脱这个问题。 我需要 userC1 构造函数中的参数。

【问题讨论】:

  • 如果TUserC1,你希望find = new T()ChangeView 中做什么?
  • 您通过签名中的new() 明确要求无参数构造函数。但是,如果您删除它,您会如何想象调用具有不同签名的构造函数?你怎么知道,例如Foo 有一个无参数构造函数,但 Bar 需要参数?你不能,现在你没有通用功能。如果您需要对父表单的引用,为什么不直接使用Control.Parent

标签: c#


【解决方案1】:

我编辑代码如下,并在我的代码中添加一个接口如下...

T Find<T>(Control container) where T : Control
    {
        for (int i = 0; i < container.Controls.Count; i++)
        {
            if (container.Controls[i] is T)
            {
                return (T)container.Controls[i];
            }
        }
        return null;
    }

public void ChangeView<T>(Func<INavigationControl, T> createTInstance) where T : Control, new()
    {
        if (transitionManager1.IsTransition)
        {
            transitionManager1.EndTransition();
        }

        transitionManager1.StartTransition(BasePanel);
        try
        {

            T find = Find<T>(BasePanel);
            if (find != null)
            {
                find.BringToFront();
            }
            else
            {
                if (createTInstance == null)
                    find = new T();
                else
                    find = createTInstance(this);
                find.Parent = BasePanel;
                find.Dock = DockStyle.Fill;
                find.BringToFront();
            }

        }
        finally
        {
            transitionManager1.EndTransition();
        }
    }




public interface INavigationControl
{
    void ChangeView<T>(Func<INavigationControl, T> createTInstance) where T : Control, new();
}

然后我添加了这段代码来调用我的更改视图方法

ChangeView(form => new Configurationn(form));

为此,我们必须如下编辑构造函数。

INavigationControl1 f1;
    public YourForm(INavigationControl1 f1) :this(){
        this.f1 = f1;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多