如何转换为传递给函数的类型?

How to cast to a type passed to a function?

我有这段代码可以将控件转换为 TextBox:

foreach (Control c in Controls)
    if (c.GetType() == typeof(TextBox))
        (c as TextBox).Clear();

我想把它封装在一个函数中,我在运行时传入类型。像这样:

public void ControlClear(ControlCollection controls, Type type) {
      foreach (Control c in controls)
          if (c.GetType() == type)
              (c as ([?])).Clear();
}
ControlClear(Controls, typeof(TextBox));

如何转换成这样的类型?

这对你有用。

你必须检查类型是否不是想要的类型,有可能是另一个容器所以你必须 运行 控件的方法以确保不会丢失任何类型的控件另一个容器,但形式相同。

你的方法应该是这样的:

public void ControlClear(Control controls,Type type)
        {
            foreach (Control c in controls.Controls)
            {
                if (c.GetType() == type)
                {
                    MessageBox.Show("true"); // Do whatever you want here. Since not all controls have Clear() method, consider using Text=string.Empty; or any other method to clear the selected type.
                }
                else
                {
                    ControlClear(c, type); // fire the method to check if the control is a container and has another type you are targeting.
                }

            }

        }

然后这样称呼它:

ControlClear(this,typeof (TextBox)); // this refers to Current form. You can pass a groupBox, panel or whatever container you want.

使用此代码:

    public void ControlClear(Control.ControlCollection controls, Type type)
    {
        foreach (Control c in controls)
            if (c.GetType() == type && c.GetType().GetMethod("Clear") != null)
                    c.GetType().InvokeMember("Clear", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, c, null);
    }

改用泛型怎么样?

public void ClearControlsOfType<T>(ControlCollection controls) where T : IClearable
    foreach(var control in controls.OfType<T>()) {
        control.Clear();
    }
}

其中 IClearable 可以是任何具有 Clear 方法的东西;如果你已经有一个确保这一点的class,你不需要一个特定的接口,但你需要在编译时确保它,否则你需要使用反射。

试试这个

    public static void ControlClear<type>(Control.ControlCollection controls) where type : Control
    {
        foreach (Control c in controls)
            if (c is type)
                ((type)c).Text = "";
    }

//===============

   ControlClear<TextBox>(Controls);