[英]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.