调用C#扩展方法而不访问它的类名

时间:2014-10-02 10:01:44

标签: c#

我有Extension方法来获取字符串值为空或检查长度为0

public static class ExExtentions
    {        
        public static bool IsEx_NotNullOrEmptyOrLenZero(this string value)
        {
            bool t = false;
            try
            {
                if (!string.IsNullOrEmpty(value) || value != "" || value.Length > 0)
                {
                    t = true;
                }
            }
            catch { t = false; }
            return t;
        }
    }

必须像ExExtentions.IsEx_NotNullOrEmptyOrLenZero(textBox1.Text)

一样调用


图片1(我做过的)

What I Have

但我想像string.IsEx_NotNullOrEmptyOrLenZero(textBox1.Text)和VS intelliSense一样打电话给像这样的图像参数NOT ref string value


图片2(我想要的内容:使用string.和参数string value进行通话而非this string value

What I want

如果我错了(请不要认真对待我在扩展程序段中的代码).net framework如何完成这项string.IsNullOrEmptry(TextBox1.Text)工作?我可以实施类似的事情吗?

2 个答案:

答案 0 :(得分:3)

您只能在扩展类型的实例上调用扩展方法。

  

我可以实施类似的事情吗?

不,您提出的语法需要向static添加class String方法,但这不是一个选项。

您可以使用扩展方法,就像它是成员一样:

string s = null;
if (s.IsEx_NotNullOrEmptyOrLenZero()) { ... }

答案 1 :(得分:3)

如果你想这样调用它,那么它不应该是一个扩展方法。在扩展类的实例上调用扩展方法,在这种情况下,它就像这样。

textBox1.Text.IsEx_NotNullOrEmptyOrLenZero()
相关问题