简体   繁体   English

如何将方法参数指定为UserControl和Interface

[英]How to specify a method parameter as UserControl and Interface

I have a constructor whit a parameter p1 which has following specifications: 我有一个构造函数,参数p1有以下规格:

  • p1 must inherit from UserControl p1必须从UserControl继承
  • p1 must realize Interface MyInterface p1必须实现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. 基类(来自第三方dll)需要UserControl,我需要访问MyInterface方法。

Thanks in advance, rhe1980 提前谢谢,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 . 看来你有一个派生自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. 客户端代码现在必须从BaseControl派生并实现接口。

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. 不太确定它在WPF设计器中运行良好,我知道它在Winforms设计器中不起作用,它需要能够构造基类的实例。 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..
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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