【问题标题】:How can i add a new Function or Property on textbox class's text property如何在文本框类的文本属性上添加新功能或属性
【发布时间】:2010-04-23 18:21:21
【问题描述】:

我想在这样的文本框的文本属性中再添加一个函数/属性。 txtControl.Text.IsEmpty();txtControl.Text.IsEmpty; 它返回我的布尔值。

我不想每次都比较空字符串。

if(txtControl.text==string.Empty) {} else {}

我们也可以做一些其他的方式

如果只是想这样做 if(txtControl.text.isEmpty){}

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    在 c# 3.0 中你可以做这样的事情..

    namespace ExtensionMethods
    {
        public static class MyExtensions
        {
            public static bool IsTextEmpty(this Textbox txtBox)
            {
                return string.IsNullOrEmpty(txtBox.Text);
            }
        }   
    }
    

    那你就可以这样使用了。

    bool isEmpty = yourTxtBox.IsTextEmpty();
    

    这将适用于您的应用程序中的所有文本框实例,前提是您已经引用了扩展方法的命名空间。如果您有自定义文本框,则将类型 TextBox 替换为自定义文本框的类型。如果你有自己的 TextBox,它可能看起来像这样..

    namespace ExtensionMethods
    {
        public static class MyExtensions
        {
            public static bool IsTextEmpty(this MyTextbox txtBox)
            {
                return string.IsNullOrEmpty(txtBox.Text);
            }
        }   
    }
    

    【讨论】:

    【解决方案2】:

    为什么不创建扩展方法:

    public static bool HasEmptyText(this TextBox textBox)
    {
        return string.IsNullOrEmpty(textBox.text);
    }
    

    那么你可以使用txtControl.HasEmptyText()

    【讨论】:

    • @david:我如何为所有的 txtboxes 实现它,我正在尝试创建自定义控件。
    • 查看Shantanu有哪些扩展方法。只要方法在引用的程序集中,它们就可以在您声明它们的所有类上工作。
    【解决方案3】:

    文本属性是一个字符串。字符串类包含一个静态方法IsNullOrEmpty() 所以你可以使用if (String.IsNullOrEmpty(txtControl.Text)) {} else {}

    选项2是在文本框上创建一个额外的属性:

    public class MyTextbox : Textbox
    {
      public bool IsEmpty
      { 
        get
        { 
          return String.IsNullOrEmpty(this.Text);
        }
      }
    }
    

    你可以这样使用它:if (txtMyTextbox.IsEmpty) {} else {}

    【讨论】:

      【解决方案4】:

      Text 属性是一个字符串,上面已经有一个IsNullOrEmpty 函数。

      【讨论】:

        【解决方案5】:

        String.IsNullOrEmpty( textControl.Text )

        【讨论】:

          猜你喜欢
          • 2020-04-07
          • 2012-07-13
          • 2011-04-29
          • 2011-09-21
          • 1970-01-01
          • 2010-11-27
          • 1970-01-01
          • 2023-03-10
          • 1970-01-01
          相关资源
          最近更新 更多