LoginSignup
0
0

More than 3 years have passed since last update.

かみ砕いてみたC#(インデクサ)

Last updated at Posted at 2019-10-04

過去に教えて頂いたインデクサをアウトプット

補足1

Javaにはない

Program.cs

using System;
using System.Collections.Generic;

namespace IndexerLesson
{
    public class Colors
    {
        private string[] data = { "赤", "青", "黄" };

         //アクセス 戻り値 this[型 引数]
        public string this[int index]{
            set{
                this.data[index] = value;
            }
            get{
                return data[index];
            }
        }

    }
}

Colors.cs

using System;
using System.Collections.Generic;

namespace IndexerLesson
{
    public class Colors
    {
        private string[] data = { "赤", "青", "黄" };

        public string this[int index]
        {
            set
            {
                this.data[index] = value;
            }
            get
            {
                return data[index];
            }
        }

    }
}

オーバーロード可能

JMonth.cs

using System;
using System.Collections.Generic;

namespace IndexerLesson
{
    public class JMonth
    {
        private string[] months = { "睦月", "如月", "弥生", "卯月", "皐月", "水無月", "文月", "葉月", "長月", "神無月", "霜月", "師走" };
        public string this[int index]
        {
            get
            {
                return months[index - 1];
            }
        }
        public int this[string name]
        {
            get
            {
                return Array.IndexOf(months, name) + 1;
            }
        }

    }
}

Profram.cs

using System;
using System.Collections.Generic;

namespace IndexerLesson
{
    class Class1
    {
        static void Main(string[] args)
        {
            JMonth jMonth = new JMonth();
            Console.WriteLine(jMonth[6]);
            Console.WriteLine(jMonth["神無月"]);
        }
    }
}

って認識です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0