如何在 C# 中使用反射强制转换对象运行时




我正在开发一个Windows应用程序,并创建了一个用于设置CommonAppearance类代码的

通用外观类

static void SetCommonAppearance(Label ctrl){ //some appearance setting code}
static void SetCommonAppearance(GridGroupingControl ctrl){ //some appearance setting code}
static void SetCommonAppearance(GradientPanel ctrl){ //some appearance setting code}
static void SetCommonAppearance(Form ctrl){ //some appearance setting code}
static void SetCommonAppearance(ComboBox ctrl){ //some appearance setting code}
static void SetCommonAppearance(CheckBox ctrl){ //some appearance setting code}
static void SetCommonAppearance(RadioButton ctrl){ //some appearance setting code}
static void SetCommonAppearance(Button ctrl){ //some appearance setting code}
public static void UseCommonTheme(Form form)
{
    List<Control> lstControls = GetAllControls(form.Controls);
    foreach (Control ctr in lstControls)
    {
       string temp2 = ctr.GetType().Name;
       switch (temp2)
       {
          case "TextBox":
               SetCommonAppearance((TextBox)ctr);
               break;
          case "AutoLabel":
               SetCommonAppearance((Label)ctr);
               break;
          case "GridGroupingControl":
               SetCommonAppearance((GridGroupingControl)ctr);
               break;
          case "ButtonAdv":
               ApplyCustomTheme((ButtonAdv)ctr);
               break;
          case "CheckBoxAdv":
               SetCommonAppearance((CheckBox)ctr);
               break;
          case "ComboBoxAdv":
               SetCommonAppearance((ComboBox)ctr);
               break;
          case "RadioButtonAdv":
               SetCommonAppearance((RadioButton)ctr);
               break;
       }
    }
}

当设置常见外观的控件应用程序较少时,这是可以接受的,但在我的应用程序中使用了许多不同类型的控件。
在方法中UseCommonTheme(Form form)而不是使用开关大小写 我们可以使用反射来投射控件吗? 类似
的东西

foreach (Control ctr in lstControls)
{
    string controlType = ctr.GetType().Name;
    SetCommonAppearance((class reference of 'controlType')ctr);
}


提前谢谢。

如果您使用的是 .net 4,则可以利用 dlr(动态语言运行时):

foreach (dynamic ctr in lstControls)
{
    SetCommonAppearance(ctr);
}

dlr 将为您解决正确的重载问题。

如果要使用反射:

var type = typeof(CommonAppearance);
var methods = type.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
foreach (Control ctr in lstControls)
{
   var setAppearanceMethod = 
        methods.FirstOrDefault(m => m.GetParameters()[0].ParameterType == ctr.GetType());
   if(setAppearanceMethod!=null)
       setAppearanceMethod.Invoke(null, new[] { ctr });
}

相关内容

  • 没有找到相关文章

最新更新