gpt4 book ai didi

c# - 如何正确使用 C# 泛型中的多重限制?

转载 作者:行者123 更新时间:2023-11-30 17:23:03 29 4
gpt4 key购买 nike

我正在尝试将 C# 泛型绑定(bind)到类和接口(interface),如下所示:

public class WizardPage<T> where T : UserControl, IWizardControl 
{
private T page;

public WizardPage( T page ) {
this.page = page;
}
}

并将其与此一起使用:

public class MyControl : UserControl, IWizardControl {
//...
}

C# 似乎无法确定 MyControl 是 T 的正确实例,因为

public class Wizard<T> where T : UserControl, IWizardControl {

private WizardPage<T> Page1;

public Wizard( MyControl control ) {
this.Page1 = new WizardPage(control);
}
}

因错误而失败

The best overloaded method match for 'Controls.WizardPage<T>.WizardPage(T)' has some invalid arguments

我是做错了什么还是这根本行不通?

最佳答案

您的 Wizard 类可能看起来像这样:

public class Wizard<T> where T : UserControl, IWizardControl
{
private WizardPage<T> Page1;

public Wizard(T control)
{
this.Page1 = new WizardPage<T>(control);
}
}

或者,如果您不需要类本身是通用的,您可以这样做:

public class Wizard
{
private WizardPage<MyControl> Page1;

public Wizard(MyControl control)
{
this.Page1 = new WizardPage<MyControl>(control);
}
}

关于c# - 如何正确使用 C# 泛型中的多重限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2431602/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com