How to properly use multiple restrictions in C # Generics?

I am trying to associate C # generics with a class and the following interface:

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

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

And use it with this:

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

Somehow C # doesn't seem to be able to decide that MyControl is a proper instance of T as

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

    private WizardPage<T> Page1;

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

with an error

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

Am I doing something wrong or is it just not working?

+3
source share
3 answers

Your class Wizardshould look something like this:

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

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

Or, if you don't need the class itself to be generic, you could do something like this:

public class Wizard
{
    private WizardPage<MyControl> Page1;

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

Wizard. :

public class MyWizard : WizardPage<MyControl>{ 
    public MyWizard( MyControl control ) : base(control) { } 
} 
0

:

this.Page1 = new WizardPage<MyControl>(control);
0

Source: https://habr.com/ru/post/1736623/


All Articles