2016-08-03 35 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

相关问题