[英]Generic class call that have parameters
In my form1 I have this method. 在我的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();
}
}
the problem is when I'm trying to call this method from user control named userC1 that have some parameters in constructor like below 问题是当我试图从名为userC1的用户控件中调用此方法时,该控件在构造函数中具有一些参数,如下所示
Form1 f;
public UserC1(Form1 f)
{
InitializeComponent();
this.f = f;
}
I call the method as follows in form 1 我在表格1中称呼该方法如下
ChangeView<UserC1>();
but above code is an error it says must be a non abstract type with public parameter less constructor in order to use it a parameter in the generic type or method. 但是上面的代码是一个错误,它说必须是具有公共参数的非抽象类型,并且要减去构造函数,才能在泛型类型或方法中使用它作为参数。
how can I over come from this problem. 我该如何克服这个问题。 I need that parameters in userC1 constructor. 我需要在userC1构造函数中使用该参数。
I edit the code as follows and add a interface to my code as follows... 我按如下方式编辑代码,并向我的代码添加接口,如下所示...
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();
}
then I added this code to call my change view method 然后我添加了这段代码来调用我的更改视图方法
ChangeView(form => new Configurationn(form)); ChangeView(form => new Configurationn(form));
to do this we have to edit the constructor ass follows. 为此,我们必须按如下方式编辑构造函数。
INavigationControl1 f1;
public YourForm(INavigationControl1 f1) :this(){
this.f1 = f1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.