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

时间:2018-06-16 12:05:59

标签: c# variables unboxing

我有这个代码将控件转换为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));

如何投射到这样的类型?

4 个答案:

答案 0 :(得分:2)

这对你有用。

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

你的方法应该是:

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.

答案 1 :(得分:2)

使用此代码:

    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);
    }

答案 2 :(得分:0)

如何使用泛型呢?

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

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

答案 3 :(得分:0)

试试这个

    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);