代码审查:CLR RegexSubstring

时间:2010-05-12 21:13:55

标签: c# .net sql-server regex clr

这会更好吗? SQL Server 2005的.NET 2.0兼容性:

public static SqlString RegexSubstring(SqlString regexpattern, 
                                       SqlString sourcetext, 
                                       SqlInt32 start_position)
{
   SqlString result = null;

   if (!regexpattern.IsNull && !sourcetext.IsNull && !start_position.IsNull)
   {
      int start_location = (int)start_position >= 0 ? (int)start_position : 0;

      Regex RegexInstance = new Regex(regexpattern.ToString());
      result = new SqlString(RegexInstance.Match(sourcetext.ToString(), 
                                                 start_location).Value);
   }

   return result;
}

这是我第一次尝试为SQL Server编写CLR函数/ etc - 是否绝对有必要使用SqlString / etc数据类型作为参数?

1 个答案:

答案 0 :(得分:1)

只需通过Refactor / Pro

运行它

给出了这个:

public static SqlString RegexSubstring(SqlString regexpattern,
                               SqlString sourcetext,
                               SqlInt32 start_position) {
    if (regexpattern.IsNull || sourcetext.IsNull || start_position.IsNull)
        return null;

    Regex RegexInstance = new Regex(regexpattern.ToString());

    return new SqlString(RegexInstance.Match(sourcetext.ToString(),
                                               (int)start_position).Value);
}

请注意,start_location未使用,因此您可能忽略了警告?

另一件事只是风格问题,但函数是否可以编写为不依赖于SqtTypes?然后代码变为:

    private static string RegexSubstring(string regexpattern, string sourcetext, int start_position) {

        if (regexpattern == null || sourcetext == null || start_position == null)
            return null;

        Regex RegexInstance = new Regex(regexpattern);
        return RegexInstance.Match(sourcetext, start_position).Value;
    }

并将其命名为:

new SqlString(RegexSubstring(regexpattern.ToString(), sourcetext.ToString(), start_position))