c# string可不可以增加新的方法? c# string 类型的方法,可不可以自己增加新的方法?比如 string.replace() 这是一个方法,我可不可以增加新的方法如: string.xxxx() 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 不可以,因为string类是sealed标记为不可继承的。除非你能让.NET开发组帮你加。 .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(); } }} 从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关键字。 2.0不可以滴用java的话说,String类是final类。。是不能被继承的。所以你没法加。3.0.。不知道 java String finalc#是sealed C#开发 怎么插入timer控件?求大神帮助。。。 filestream读取大文件的问题 刚起步 这个意图如何实现 能否用MSCOMM控件实现两台电脑文件传输??? 邮箱格式验证 象这样的导航是怎么做的? .net 中有没有语句提示的快捷键 包吃包住.试用期2个月4K.试用期过后6K,8K,9K,抑或... 各位帮忙!一个奇怪的问题! ListView or GridView vs打包问题
{
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();
}
}
}
定义扩展方法,首先要确保你的项目所使用的.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关键字。
所以你没法加。
3.0.。不知道
c#是sealed