7

当我遍历表单上的一堆不同控件时,而不是尝试访问 Text 属性:

String text = String.Empty;
foreach(Control control in this.Controls)
{
   try
   {
      text = control.Text;
   }
   catch(Exception exception)
   {
      // This control probably doesn't have the Text property.
      Debug.WriteLine(exception.Message);
   }
}

有没有办法确定给定控件是否具有 Text 属性?像这样的东西:

String text = String.Empty;
foreach(Control control in this.Controls)
{
   if(control has Text property)
   {
      text = control.Text;
   }
}

我绝对鄙视 Try/Catch 块(当然,除非没有更好的选择)。

4

3 回答 3

8

所有Control对象都有一个Textproperty,因此使用反射来确定它是没有意义的。它总会回来true的。

您的问题实际上是某些控件从其Text属性中抛出异常,因为它们不支持它。

如果您还希望能够使用事先不知道的自定义控件,则应坚持当前的解决方案并捕获异常。但是,您应该捕获抛出的特定异常,例如NotSupportedException.

如果您只遇到事先知道的控件,则可以选择您知道具有工作Text属性的控件。例如:

public static bool HasWorkingTextProperty(Control control)
{
    return control is Label
        || control is TextBox
        || control is ComboBox;
}

var controlsWithText = from c in this.Controls
                       where HasWorkingTextProperty(c)
                       select c;

foreach(var control in controlsWithText)
{
    string text = control.Text;
    // Do something with it.
}

如果您实现自己的自定义控件,这些控件可能有也可能没有Text属性,那么您可以从指示这一点的基类派生它们:

public abstract class CustomControlBase : Control
{
    public virtual bool HasText
    {
        get { return false; }
    }
}

public class MyCustomControl : CustomControlBase
{
    public override bool HasText
    {
        get { return true; }
    }

    public override string Text
    {
        get { /* Do something. */ }
        set { /* Do something. */ }
    }
}

public static bool HasWorkingTextProperty(Control control)
{
    return (control is CustomControlBase && ((CustomControlBase)control).HasText)
        || control is Label
        || control is TextBox
        || control is ComboBox;
}
于 2013-03-06T00:06:52.253 回答
5

你的问题是如何确定 Control 是否有 Text 属性,所以这里是你如何使用反射来做到这一点:

control.GetType().GetProperties().Any(x => x.Name == "Text");

编辑:如果你看一下这个Control类,你会看到它有一个Text属性。

现在,如果某些覆盖类的自定义控件在访问属性Control时抛出异常,则违反了Liskov 替换原则。在这种情况下,我建议您确定这些控件,尽管您所做的似乎很好。Text

于 2013-03-06T00:02:10.320 回答
3

看一下这个:

private void Form1_Load(object sender, EventArgs e)
{
     foreach (Control ctrl in this.Controls)
     {
          PropertyInfo[] properties = ctrl.GetType().GetProperties();
          foreach(PropertyInfo pi in properties)
              if (pi.Name == "Text")
              { 
                    //has text
              }
       }

}
于 2013-03-06T00:00:29.120 回答