简体   繁体   中英

How to specify a method parameter as UserControl and Interface

I have a constructor whit a parameter p1 which has following specifications:

  • p1 must inherit from UserControl
  • p1 must realize Interface MyInterface

Example:

public class ClassA: UserControl, MyInterface
{ ... }

Anyone an idea how I can define the method.

The constructor looks like this:

public MyClass(UserControl uc) : base(uc)
{ 
   // access to MyInterface-Methods
}

The base class (which is from a third party dll) requires a UserControl, I need access to the MyInterface Methods.

Thanks in advance, rhe1980

After my comment, what comes to my mind is only a

public void MyMethod<T>(T param) where T : UserControl, MyInterface
{
     // do something here
}

[EDIT] OK, no one has taken a stab on it in the meantime, so I'll try to follow. It seems you have a class derived from some kind of base class taking the UserControl . Here's what you can try:

public interface ITest
{
    void AwesomeInterface();
}

//As far as I could tell, this class is in some 3rd party DLL
public class TheBaseClass
{
    protected TheBaseClass(UserControl uc)
    {

    }
}

//Now this should work just fine
public class ClassB<T> : TheBaseClass where T : UserControl, ITest
{
    public ClassB(T param) : base(param)
    {
        param.AwesomeInterface();
    }
}

You do it by declaring an abstract base class:

public abstract class BaseControl : UserControl, IMyInterface {}

And declare your constructor argument of that type. The client code now must derive from BaseControl and implement the interface.

Not so sure that will work well in the WPF designer, I know that it won't work in the Winforms designer, it needs to be able to construct an instance of the base class. Nor does a generic work, for the same reason. In which case you must resort to a runtime check:

public MyClass(UserControl uc) : base(uc)
{ 
    if (uc as IMyInterface == null) {
        throw new ArgumentException("You must implement IMyInterface", "uc");
    }
    // etc..
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM