Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.88/8: Рейтинг темы: голосов - 8, средняя оценка - 4.88
4 / 4 / 0
Регистрация: 18.07.2012
Сообщений: 32
1

Передать массив из класса в класс

27.08.2012, 15:40. Показов 1612. Ответов 2
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Добрый день, привет всем! Помогите пожалуйста решить задание! Нужно передать массив (не списком list) работников в класс Department, который описан отдельным классом "Employee" (Работник). Класс, описывающий работника, указывает его имя, фамилию, должность и оклад.
У меня ошибка при добавлении работников .. Помогите пожалуйста!!
C#
1
2
3
4
5
6
7
8
9
    public void Add(string name, string surname, string posada, double oklad)
        {
            Array.Resize(ref arrEmployee, arrEmployee.Length + 1);
 
            this.arrEmployee[arrEmployee.Length - 1].Name = name;
            this.arrEmployee[arrEmployee.Length - 1].Surname = surname;
            this.arrEmployee[arrEmployee.Length - 1].Posada = posada;
            this.arrEmployee[arrEmployee.Length - 1].Oklad = oklad;
        }
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
using System;
 
namespace ConsoleApplication3
{
    public class Department
    {
        private string name = "Unknown";
        private string tel = "";
        public Employee[] arrEmployee = new Employee[0];
 
        public Department()
        {}
 
        public Department(string name, string tel)
        {
            this.name = name;
            this.tel = tel;
        }
 
        public void Add(string name, string surname, string posada, double oklad)
        {
            Array.Resize(ref arrEmployee, arrEmployee.Length + 1);
 
            this.arrEmployee[arrEmployee.Length - 1].Name = name;
            this.arrEmployee[arrEmployee.Length - 1].Surname = surname;
            this.arrEmployee[arrEmployee.Length - 1].Posada = posada;
            this.arrEmployee[arrEmployee.Length - 1].Oklad = oklad;
        }
        public void Print()
        {
            for (int i = 0; i < arrEmployee.Length; i++)
            {
                arrEmployee[i].Print();
            }
     
        }
        public Employee this[int pos]
        {
            get
            {
                if (pos < 0 || pos > 10)
                    throw new IndexOutOfRangeException("Wait a minute! Index out of range");
                else
                    return (arrEmployee[pos]);
            }
            set
            {
                arrEmployee[pos] = value;
            }
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public string Tel
        {
            get { return tel; }
            set { tel = value; }
        }
 
    }
 
    public class Employee
    {
        private string name;
        private string surname;
        private string posada;
        private double oklad;
 
        public Employee()
        {
            name = "Unknown";
            surname = "Unknown";
            posada = "Unknown";
            oklad = 0;
        }
 
        public Employee(string name, string surname, string posada, double oklad)
        {
            this.name = name;
            this.surname = surname;
            this.posada = posada;
            this.oklad = oklad;
        }
        //public void Add()
        //{
        //   Console.WriteLine("Add Employee:");
        //   for (int i = 0; i < employees.Length; i++)
        //   {
        //   Console.WriteLine("Enter name:");
        //   name = Console.ReadLine();
        //   Console.WriteLine("Enter surname:");
        //   surname = Console.ReadLine();
        //   Console.WriteLine("Enter posada:");
        //   posada = Console.ReadLine();
        //   Console.WriteLine("Enter oklad:");
        //   oklad = Convert.ToDouble(Console.ReadLine());
        //   count++;
        //   }
        //}
 
        public void Print()
        {
            for (int i = 0; i < 1; i++)
            {
 
            Console.WriteLine("\nPrint Employee Name: {0}", name);
            Console.WriteLine("surname: {0}\nposada: {1}\noklad {2}", surname, posada, oklad);
            }
        }
        //public void Del()
        //{
        //   for (int i = 0; i < employees.Length; i++)
        //   {
 
        //       count--;
        //   }
        //}
 
        public string Name
        {
            get { return name; }
            set {name = value; }
        }
        public string Surname
        {
            get { return surname; }
            set { surname = value; }
        }
        public string Posada
        {
            get { return posada; }
            set { posada = value; }
        }
        public double Oklad
        {
            get { return oklad; }
            set { oklad = value; }
        }
        //    public int GetCount()
        //    {
        //        return count;
        //    }
        //    public string this [int index]  
        //    {
        //        get 
        //        {
        //            if (index >= 0 && index < MAX_EMPLOYEES)
        //                {
        //                    return employees[index];
        //                }
 
        //            return null;
        //        }
        //        set
        //        {
        //            if (index >= 0 && index < MAX_EMPLOYEES)
        //            {  
        //                employees[index] = value;
        //            }
        //        }
        //    }
        //}
 
 
 
 
 
        class TestDepartment
        {
            static void Main()
            {
                Department arrDep = new Department();
                Employee arrEmp = new Employee();
                //arrDep[0].name = "a";
                //arrEmp.Print();
                arrDep.Add("a","b","c",1);
                arrDep.Print();
                //arrDep[0] = new Employee("Vasya", "Pupkin", "Menedzer", "1");
 
                //Console.WriteLine("Indexer...");
                //for(int i = 0; i < 3; i++)
                //   {
                //        Console.WriteLine("Car number {0}:", i+1);
                //        Console.WriteLine("Name: {0} Prizvuche: {1}, Year: {2}");
 
                //   }
                //arrEmp.Add();
                //arrEmp.Del();
                //arrEmp.Print();
 
                //arrEmp[0] = "AAA";
                //arrEmp[1] = "BBB";
                //arrEmp[2] = "CCC";
                //arrEmp[3] = "DDD";
                //Console.WriteLine("\nEmployee {0} and {1} and {2} and {3}", arrEmp[0], arrEmp[1], arrEmp[2], arrEmp[3]);
            }
        }
    }
}
1
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
27.08.2012, 15:40
Ответы с готовыми решениями:

Как передать массив textBox из класса в класс
Хочу использовать класс и сократить часть кода но не получается передать массив из класса в класс....

Передать переменную из класса в класс
Добрый день, следующая задача передать переменную из класса А в класс В class_a.h #ifndef...

Нужно передать значение из класса в класс
import sys from PyQt5 import QtWidgets, QtGui class Win2(QtWidgets.QMainWindow): #...

Передать обьект класса в другой класс.
Подскажите как лучше. Заранее спасибо!

2
556 / 510 / 25
Регистрация: 23.07.2009
Сообщений: 2,359
Записей в блоге: 1
27.08.2012, 16:02 2
массив ты раздвинул, а имплуя туда кто добавлять будет? сперва создай, добавь, а потом уже значения ему присваивай. до того там, в массиве - null

Добавлено через 16 минут
Цитата Сообщение от Vitia28 Посмотреть сообщение
Добрый день, привет всем! Помогите пожалуйста решить задание! Нужно передать массив (не списком list) работников в класс Department, который описан отдельным классом "Employee" (Работник). Класс, описывающий работника, указывает его имя, фамилию, должность и оклад.
У меня ошибка при добавлении работников .. Помогите пожалуйста!!
C#
1
2
3
4
5
6
7
8
9
    public void Add(string name, string surname, string posada, double oklad)
        {
            Array.Resize(ref arrEmployee, arrEmployee.Length + 1);
 
            this.arrEmployee[arrEmployee.Length - 1].Name = name;
            this.arrEmployee[arrEmployee.Length - 1].Surname = surname;
            this.arrEmployee[arrEmployee.Length - 1].Posada = posada;
            this.arrEmployee[arrEmployee.Length - 1].Oklad = oklad;
        }
C#
1
2
3
            Array.Resize(ref arrEmployee, arrEmployee.Length + 1);
 this.arrEmployee[arrEmployee.Length - 1] = new Employee();
...
1
4 / 4 / 0
Регистрация: 18.07.2012
Сообщений: 32
27.08.2012, 16:10  [ТС] 3
novi4ok, Спасибо тебе большое!!
1
27.08.2012, 16:10
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
27.08.2012, 16:10
Помогаю со студенческими работами здесь

Передать экземпляр класса в другой класс
Подскажите как сделать класс который будет принимать как входной параметр, экземпляр других классов?

Как передать параметр из класса в класс?
всем привет, как передать параметр из класса в класс(этот параметр List): class word:paragraf ...

Передать в класс список экземпляров другого класса
подскажите пожалуйста как это реализовать? есть класс: public class Timefr60 { ...

Как передать значение переменной из класса в класс?
Здравствуйте. Я бы хотел в этой программе передать значение TOTAL_PSU в другой класс, чтобы...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru