例如我给string类型定义一个扩展方法shift,用来删除string开头指定数量的字符,并返回被删除的字符        /// <summary>
        /// 从字符串的开头删除指定个数的字符,并返回被删除的字符
        /// </summary>
        /// <param name="text">需要处理的字符串</param>
        /// <param name="length">要删除的字符个数</param>
        /// <returns>返回被删除的字符串</returns>
        public static string Shift(this ref string text,int length)
        {
            //进行一些字符串处理                     return text;           
        }理论上来说是这样写的,但是this和ref关键字不能同时使用,难道我要在string的Shift方法中再次传递ref string?
像这样? public static string Shift(this string text, ref string shifttext, int length)这样写可以是可以,总感觉不太优雅,忘赐教!

解决方案 »

  1.   

            public static string Shift(ref string text,int length)
      

  2.   

    不是有了string返回值吗,为什么还要ref
      

  3.   


    用ref直接修改字符串,返回值返回被删除的字符,类似javascript里面数组的shift方法,我在想用指针可以不可以
      

  4.   

    public static string[] Shift(this string text,int length)返回string数组,包含修改的和被删除的
      

  5.   

    ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。例如:  复制代码 
    class RefExample
    {
        static void Method(ref int i)
        {
            i = 44;
        }
        static void Main()
        {
            int val = 0;
            Method(ref val);
            // val is now 44
        }
    }
     传递到 ref 参数的参数必须最先初始化。这与 out 不同,后者的参数在传递之前不需要显式初始化。有关更多信息,请参见 out。尽管 ref 和 out 在运行时的处理方式不同,但在编译时的处理方式相同。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的,因此将不会编译以下代码:  复制代码 
    class CS0663_Example 
    {
        // Compiler error CS0663: "cannot define overloaded 
        // methods that differ only on ref and out".
        public void SampleMethod(ref int i) {  }
        public void SampleMethod(out int i) {  }
    }
     但是,如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两个参数,则可以进行重载,如下例所示:  复制代码 
    class RefOutOverloadExample
    {
        public void SampleMethod(int i) {  }
        public void SampleMethod(ref int i) {  }
    }
     备注
    属性不是变量,因此不能作为 ref 参数传递
      

  6.   

    我认为扩展方法是一个很好用的语法糖,它让你感觉好像是扩展了一个类一样。所以在给一个类添加扩展方法时,应该考虑这里的类的限制和惯例。
    string是不可改变的类,所以我觉得它的扩展方法也不应该能改变自身。我的建议是略微修改一下需求,改为:
    public static string Shift(this string text, out string shifttext, int length)
    这样返回值是修改后的string,而输出参数shifttext是删除的字符串。
    这样是不是更符合string的特点呢?
      

  7.   

    string 不好用,特殊的引用类型,=号的运算是赋值
    用StringBuilder可以    class Program
        {
            static void Main(string[] args)
            {
                StringBuilder s = new StringBuilder("123456789");
                Console.WriteLine("返回值:{0},修改之后值:{1}", s.Shift(3), s);
                Console.ReadKey();
            }
        }
        static class MyClassMethod
        {
            public static string Shift(this StringBuilder s, int length)
            {
                string result = s.ToString().Substring(0, length);
                s = s.Remove(0, length);
                return result;
            }
        }