在我们的代码快速方法实现如下?实施快速方法有什么好处?

时间:2012-04-15 16:07:34

标签: c# .net performance mvvm-light

呼吁快速方法是:

QuickMethods.IsFullyEmpty(CompanyName.Text) ||
                QuickMethods.IsFullyEmpty(UsernameText.Text) ||
                QuickMethods.IsFullyEmpty(PasswordText.Password)

并且实施是:

public static class QuickMethods
    {
        public static bool IsFullyEmpty(string s)
        {
            if (string.IsNullOrEmpty(s.Trim()))
                return true;
            return false;
        }
    }

有没有可用的选项?如果是,那怎么样?

5 个答案:

答案 0 :(得分:3)

我认为好处是该方法还检查只包含空格的字符串,但如果您正在寻找“选项”,那么在.NET 4.0中您可以使用string.IsNullOrWhiteSpace()并避免调用{ {1}}。

答案 1 :(得分:1)

为什么不将此验证逻辑提取到方法(或属性)中?

class TheViewModel
{
    public string CompanyName { get; set; }
    public string UsernameText { get; set; }
    public string PasswordText { get; set; }

    private bool Validate()
    {
        bool result = !QuickMethods.IsFullyEmpty(CompanyName) &&
                !QuickMethods.IsFullyEmpty(UsernameText) &&
                !QuickMethods.IsFullyEmpty(PasswordText);
        return result;
    }
}

答案 2 :(得分:0)

这比组合的IsNullOrEmpty(s.Trim())

更具可读性

改进版本会提供一些关于错误的反馈。

答案 3 :(得分:0)

主要好处是封装了IsFullyEmpty的实现。这改进了您的设计,因为您只需要在一个组件中更改IsFullyEmpty的实现(而不是每个调用IsFullyEmpty的组件)。当您(或其他团队成员)开发新组件时,您可以避免因重新实现IsFullyEmpty()逻辑而导致的错误(即,团队中的新程序员可能会忘记首先修剪字符串) )。还有重构的好处,例如,如果这是一个移动到.NET 4.0的.NET 2.0项目,你可以将IsFullyEmpty重构为:

public static class QuickMethods 
{ 
   public static bool IsFullyEmpty(string s) 
   { 
     return string.IsNullOrWhitespace(s);
   }
}

答案 4 :(得分:0)

您可以利用paramsextension method的优势。

public static class QuickMethods
    {
        public static bool IsFullyEmpty(this string s, params string[] others)
        {

            if(s != null && s.trim().length > 0) {
               return false;
            }

            for(String o : others) {
              if(o != null && o.trim().length > 0)) {
               return false;
              }
            }

            return true;         
        }
    }
相关问题