实例 C#3.0与C#2.0相比之新特性(二)---扩展方法
这是个非常酷的新特性。你可以给方法在编译的时候指定的参数类型。比如说你想添加一个方法,参数类型为string类型。特别值得注意的是一定要在参数前面加上“this”关键字。还是来个Demo吧:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class ExtendMethod : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string Name = "qiujuan";
string text=Name.SayHello();
Response.Write(text);
}
}
//扩展方法必须在顶级的静态类中定义,不能在嵌套类中定义
public static class ExtendClass
{
public static string SayHello(this string userName)
{
return string.Format("Hello,{0}", userName);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class ExtendMethod : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string Name = "qiujuan";
string text=Name.SayHello();
Response.Write(text);
}
}
//扩展方法必须在顶级的静态类中定义,不能在嵌套类中定义
public static class ExtendClass
{
public static string SayHello(this string userName)
{
return string.Format("Hello,{0}", userName);
}
}
}