[英]How to specify a method parameter as UserControl and Interface
我有一个构造函数,参数p1有以下规格:
例:
public class ClassA: UserControl, MyInterface
{ ... }
任何人都知道如何定义方法。
构造函数如下所示:
public MyClass(UserControl uc) : base(uc)
{
// access to MyInterface-Methods
}
基类(来自第三方dll)需要UserControl,我需要访问MyInterface方法。
提前谢谢,rhe1980
在我的评论之后,我想到的只是一个
public void MyMethod<T>(T param) where T : UserControl, MyInterface
{
// do something here
}
[编辑]好的,在此期间没有人对它进行过攻击,所以我会尝试跟进。 看来你有一个派生自UserControl
某种基类的类。 这是你可以尝试的:
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();
}
}
您可以通过声明一个抽象基类来完成它:
public abstract class BaseControl : UserControl, IMyInterface {}
并声明该类型的构造函数参数。 客户端代码现在必须从BaseControl派生并实现接口。
不太确定它在WPF设计器中运行良好,我知道它在Winforms设计器中不起作用,它需要能够构造基类的实例。 出于同样的原因,通用工作也不是。 在这种情况下,您必须求助于运行时检查:
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.