如何将URL处理方法改写为字符串扩展方法并正确调用?
正确改写字符串扩展方法及调用方式
你之前的扩展方法定义方向搞反了——扩展方法的this参数应该标记你要扩展的目标类型,也就是我们要给string对象添加操作方法,所以this要修饰string value(即待处理的字符串),而不是前缀/后缀参数。
步骤1:定义正确的扩展方法
创建一个静态类存放扩展方法(扩展方法必须在静态类中,且自身为静态方法):
public static class StringExtensions { // 给string扩展:移除指定前缀 public static string RemovePrefix(this string value, string prefix) { if (string.IsNullOrEmpty(prefix) || !value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { return value; } return value.Substring(prefix.Length); } // 给string扩展:移除指定后缀字符 public static string RemovePostfix(this string value, char postfix) { if (string.IsNullOrEmpty(value)) { return string.Empty; } if (value[^1] != postfix) // 用C# 8.0+的索引语法更简洁,等价于value[value.Length - 1] { return value; } return value.Substring(0, value.Length - 1); } }
步骤2:链式调用扩展方法
改写后的调用逻辑和原代码效果完全一致,但更直观易读:
var urlSections = requestedPath.RemovePrefix("/").RemovePostfix('/').Split('/');
为什么原来的定义不对?
你之前写的public string RemovePrefix(this string prefix, string value),相当于给前缀字符串扩展了一个方法,而不是给待处理的requestedPath(目标字符串)扩展方法,这完全不符合需求。正确的逻辑是:让目标字符串自己调用RemovePrefix/RemovePostfix,传入前缀/后缀参数。
内容的提问来源于stack exchange,提问作者lakykytik
相关产品推荐
相关产品推荐

