Индексатор object - C#

Узнай цену своей работы

Формулировка задачи:

Здравствуйте! Не получается запустить программу, подскажите что делать с индексатором "object".
using System;
 
namespace Olio
{
    class Test
    {
        private object[] array;
        
        public Test(int size)
        {
            array = new string[size];
        }
        public object this[string index]
        {
            get {
                
            }
            set {
                
            }
        }
    }
 
    class Program
    {
        static void Main()
        {
            Test test = new Test(3);
            test["int"] = 123;
            test["decimal"] = 456.78;
            test["text"] = "Hello World!";
 
            double summa = (double)(int)test["int"] + (double)test["decimal"];
            Console.WriteLine("Summa = {0}", summa);
        }
    }
}

Решение задачи: «Индексатор object»

textual
Листинг программы
using System;
using System.Collections.Generic;
 
namespace ConsoleAppTest
{
    class Test
    {
        Dictionary<string, object> data;
 
        public Test(int size) {
            data = new Dictionary<string, object>(size);
        }
 
        public object this[string index] {
            get {
                return data[index];
            }
            set {
                if (data.ContainsKey(index))
                    data[index] = value;
                else
                    data.Add(index, value);
            }
        }
    }
 
    class Program
    {
        internal static void Main() {
            Test test = new Test(3);
            test["int"] = 123;
            test["decimal"] = 456.78m;
            test["text"] = "Hello World!";
            Console.WriteLine((decimal)(test["decimal"]));
        }
    }
}

ИИ для рефератов и докладов


  • Экспорт Word по ГОСТу
  • Минимум 80% уникальности текста
  • Поиск релевантных источников в интернете
  • Готовый документ за 2 минуты

Оцени полезность:

14   голосов , оценка 3.786 из 5
Похожие ответы