扩展方法/对象与集合初始化器

扩展方法

静态类包含的方法必须都是静态方法。

扩展方法允许我们在不改变原有类的情况下,扩展现有类型中的实例方法,是一种编译时的技术。

 

 

publicstaticclassMyClass //必须是静态类

    {

        publicstaticvoid getdata(thisstring s)  //静态方法,this不可少

        {

            Console.WriteLine(s.Length);

        }

    }

   

    classProgram

    {

        staticvoid Main(string[] args)

        {

            string str = "rxm";

            str.getdata(); //实例方法的调用!

            Console.Read();

        }

}

 

 

对象与集合初始化器:

publicclassPoint

    {

        int x, y;

 

        publicint X

        {

            get { return x; }

            set { x = value; }

        }

       

        publicint Y

        {

            get { return y; }

            set { y = value; }

        }

    }

   

    classProgram

    {

        staticvoid Main(string[] args)

        {

            Point p = newPoint();

            p.X = 9;

            p.Y = 89;

 

            Point p1 = newPoint { X = 9, Y = 89 };  //对象初始化器

 

            List<int> nums = newList<int>();

            nums.Add(3);

            nums.Add(4);

 

            List<int> nums1 = newList<int> { 3, 4 };  //集合初始化器

 

            Console.WriteLine(p.Y==p1.Y);

            Console.WriteLine(nums[1]==nums1[1]);

            Console.Read();

        }

    }

原文地址:https://www.cnblogs.com/hometown/p/3204235.html