2016-08-03 33 views
0

我有2個類的程序,我試圖創建一個方法,它格式化另一個類的一些System.Windows.Forms對象。C#創建一個通用的方法參數

這是我的代碼:

internal void Format(Panel component, int width, int height, int x, int y) 
    { 
     component.Width = width; 
     component.Height = height; 
     component.Left = x; 
     component.Top = y; 
    } 

    internal void Format(GroupBox component, int width, int height, int x, int y) 
    { 
     component.Width = width; 
     component.Height = height; 
     component.Left = x; 
     component.Top = y; 
    } 

    internal void Format(Button component, int width, int height, int x, int y) 
    { 
     component.Width = width; 
     component.Height = height; 
     component.Left = x; 
     component.Top = y; 
    } 

我可以爲所有需要的對象類型相同的方法(使用不同的對象參數),但也許有與只有一個方法與創建它的方式「所有對象類型的「一般/總體/通用」參數

+1

他們都從'Control'類繼承,你可以使用這個基類相反,我會建議檢查,要麼拋出一個異常,如果對象是不是你支持或返回false或東西的人之一。 – Jite

+0

它的工作原理!也感謝您的建議,我會的! – Mishaka

+0

沒問題。正如@Ephraim發佈了一個關於它的答案,id建議標記爲正確的答案。 :) – Jite

回答

1

嘗試使用Control作爲參數數據類型,因爲所有控件都從此類繼承。

internal void Format(Control component, int width, int height, int x, int y) 
{ 
    component.Width = width; 
    component.Height = height; 
    component.Left = x; 
    component.Top = y; 
} 
+0

謝謝你的作品! – Mishaka

相關問題