การใช้ Indexer ในการเข้าถึงข้อมูลภายใน Class

 

1.Create Project with C#.Net

1
 

2.Select template with Console Application

2
 

3.Create new item

            Rigth Click Project Name and select Add select Class

3
 

4.Select Class and rename Class in Name click Add

4
 

Coding in Class

using System;

using System.Collections.Generic;

using System.Text;

 

namespace ConsoleApplication1

{

    class Class1

    {

        string[] animal ={"Cat","Bat","Rad","Dog","Pig" };

        private int getAnimalCount(string strAnimal)

        {

            int i = 0;

            foreach(string strName in animal)

            {

                if (strName == strAnimal)

                {

                    i += 1;

                    break;

                }

            }

            return i;

        }

        public int this[string strAnimal]

        {

            get { return getAnimalCount(strAnimal); }

        }

    }

}

//——————————————————————————————————

//——————————————————————————————————

Coding in Progarm.cs

using System;

using System.Collections.Generic;

using System.Text;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            Class1 c = new Class1();

             Console.WriteLine("Cat :"+c["Cat"]);

             Console.WriteLine("Bat :" + c["Bat"]);

             Console.WriteLine("Rad :" + c["Rad"]);

             Console.WriteLine("Dog :" + c["Dog"]);

             Console.WriteLine("Pig :" + c["Pig"]);

             Console.WriteLine("——————–");

        }

    }}

5

กรุณา Comment สักหน่อยเถอะ จะได้ปรับปรุ่งให้ดีขึ้น

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / เปลี่ยนแปลง )

Twitter picture

You are commenting using your Twitter account. Log Out / เปลี่ยนแปลง )

Facebook photo

You are commenting using your Facebook account. Log Out / เปลี่ยนแปลง )

Google+ photo

You are commenting using your Google+ account. Log Out / เปลี่ยนแปลง )

Connecting to %s