c#  string 类型的方法,
可不可以自己增加新的方法?
比如 string.replace() 这是一个方法,
我可不可以增加新的方法
如:  string.xxxx()

解决方案 »

  1.   

    不可以,因为string类是sealed标记为不可继承的。除非你能让.NET开发组帮你加。
      

  2.   

    .NET 3.0可以,叫做“扩展方法”namespace WindowsFormsApplication1
    {
        static class ExtensionMethods
        {
            public static void Show(this string str)
            {
                MessageBox.Show(str);
            }
        }    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        private void Button1_Click(object sender, EventArgs e)
            {
                "Zswang 路过".Show();
            }
        }
    }
      

  3.   

    从C# 3.0开始,引入了一个新的东西,叫扩展方法。
    定义扩展方法,首先要确保你的项目所使用的.NET版本在3.0以及以上。然后,在你的项目中随便创建一个static class,比如:public static class MyStringExtender
    {
        public static bool ContainsA (this string src)
        {
            if (src == null || src.Equals(string.Empty))
                  return false;
            return src.IndexOf("A") >= 0;
        }
    }然后,在你使用string对象的时候,直接就可以点出“ContainsA”方法:string mystr = "this is A test";
    Console.WriteLine(mystr.ContainsA());
    扩展方法的关键:类和方法都应该是静态的;参数中使用this关键字。
      

  4.   

    2.0不可以滴用java的话说,String类是final类。。是不能被继承的。
    所以你没法加。
    3.0.。不知道
      

  5.   

    java  String final
    c#是sealed