今天在一个asp.net mvc的教材上看到这样个类:
public static class CaptchaHtmlHelper
    {
        internal const string SessionKeyPrefix = "__Captcha";
        private const string ImgFormat = "<img src=\"{0}\" />";        public static string Captcha(this HtmlHelper html, string name)
        {
            string challengeGuid = Guid.NewGuid().ToString();            var session = html.ViewContext.HttpContext.Session;
            session[SessionKeyPrefix + challengeGuid] = MakeRandomSolution();            var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
            string url = urlHelper.Action("Render", "CaptchaImage", new { challengeGuid});            return string.Format(ImgFormat, url) + html.Hidden(name, challengeGuid);
        }        public static string MakeRandomSolution()
        {
            Random rng = new Random();
            int length = rng.Next(5, 7);
            char[] buf = new char[length];            for (int i = 0; i < length;i++ )
                buf[i] = (char)('a' + rng.Next(26));            return new string(buf);
        }
    }平时情况,我知道“this"就是代码当前这个对象,但这里的public static string Captcha(this HtmlHelper html, string name)其中的this是什么含义呢?为什么要这样写呢?

解决方案 »

  1.   

    这个是扩展方法是必须要这样去写!去msdn里面去看看3.5的扩展方法!!
      

  2.   

    http://msdn.microsoft.com/zh-cn/library/bb383977.aspx
      

  3.   

    C#3.0里的扩展方法的THIS
    static class MyClass
    {
    static void Print(this stirng s)
    {
    Console.WriteLine(s);
    }
    static void Main(string[] args)
    {
    stirng str = "dsdgs";
    str.Print();
    }
    }
    //注意上面的类是静太的class A
    {
    public A()
    { }
    public A(string name):this()// 2调用有参的构造函数先去调用无参的
    {}
    }引用当前类的成员变量:this.name //3 
    将对象作为参数传递到其他方法 : add(this); //4 
    声明索引器: //5
    public int this [int param]
    {
    get { return array[param]; }
    set { array[param] = value; }
    }Using有3种用法:Using System;//引用命名空间
    using RES = System.Text.RegularExpressions.Regex; //简化命名空间
    using(DataSet ds = new DataSet())//using语名块,执行代码块后自动销毁该对象
    {}
     new关键字有3种用法:泛型约束,表T类型一定是引用类型且要带一个无参的构造函数 
    class A<T> where T : new()
    { } 
    实例化对象  Stuent stu = new Student();隐藏从基类继承的同名成员和同名方法:
    public class DerivedC : BaseC
    { public class BaseC 
    { public int x;
    public void Invoke() {}
    }new public int x; 
    new public void Invoke() {}
    }
     本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zhlu880516/archive/2008/07/17/2663714.aspx
      

  4.   

    .NET 3.0的新语法。比如string类,因为它是一个不能继承的类,要想增加方法,只能这么做了。