c# - 如何判断控件是否有Text属性

标签 c# .net winforms xaml

当我在 Form 上迭代一堆不同的控件时,而不是尝试访问 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 block (当然,除非没有更好的选择)。

最佳答案

所有 Control 对象都有一个 Text property ,因此没有必要使用反射来确定它。它将始终返回 true

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

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

如果您只遇到过您事先知道的控件,则可以选择您知 Prop 有有效 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;
}

关于c# - 如何判断控件是否有Text属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15236462/

相关文章:

c# - 使用 SSL 连接到 Postgresql

java - C# 和 Java Web 服务集成

c# ListView 标题的单独上下文菜单

c# - 在 C# 中单击时清除单个文本框?

c# - 如何检测取消 FormClosing 事件的父表单?

c# FileInfo exists 为文件的网络路径返回 false

c# - Observable<IEnumerable> 获取序列元素之间的差异

c# - 如何调试异步代码?

c# - SqlConnection 和 SqlConnectionStringBuilder 的区别

c# - WCF 数据服务身份验证