2016-01-20 36 views
0

我具有從用戶控件派生的用戶控件類上呼叫的用戶控制方法的用戶控件對象

[ComVisible(true)] 
public class MyUserControl : UserControl 

它包含了一個方法,我稱爲初始化():public void Initialize() 在另一個類中,我需要使用一個MyUserControl,但我想聲明和使用通用的UserControl對象。這樣,即使有一個新的和不同的用戶控件,我也可以重用這個類(比如MyUserControl2)。

所以我宣佈這個類的成員,

private static UserControl _userControl; 

這裏是構造

public CTPManager(UserControl userControl, string Title, MsoCTPDockPosition Position) 
{ 
    //stuff 

    _userControl = userControl; 
    _title = Title; 
    _position = Position; 
} 

第一個問題:是否有可能在以後實例化這個類:

MyUserControl newControl = new MyUserControl(); 
CTPManager newCTP = new CTPManager(newControl, "window title", etc.); 

如果是這樣,我可以調用MyUserControl newControl的Initialize()方法,因爲我只需要執行SE的CTPManager類中兩個電話:

CustomTaskPaneFactory.CreateCustomTaskPane(typeof(UserControl), _title, _EXCELApp.ActiveWindow)); //-> this one will be ok because of CreateCustomTaskPane signature 
_userControl.Initialize //-> that is what I would like to be able to do ! 

非常感謝您的任何答案或建議

回答

0

可以使用的MethodInfo:

//Get the method information using the method info class 
MethodInfo mi = _userControl.GetType().GetMethod("Initialize"); 

//Invoke the method 
mi.Invoke(_userControl, null); 
+1

謝謝你,我選擇了這一個作爲ansswer但我敢肯定,@redlum答案是最好的做法。 – Yasston

+0

我相信@redlum答案也是最好的做法,但並不總是可行的 –

0

創建初始化()方法的接口。實現接口。將該控件作爲該界面保存在CTPManager中。或者,如果你想將它存儲爲用戶控件,那麼你可以將它轉換爲類型你想要的:

var init = (InitializerInterface)_userControl; 
if (init != null) ...