Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/15: Рейтинг темы: голосов - 15, средняя оценка - 4.67
 Аватар для supra7sky
15 / 15 / 5
Регистрация: 07.02.2013
Сообщений: 123

Не реализуется интерфейс IList<T>. Не позволяет использовать модификаторы public

15.12.2013, 21:29. Показов 3125. Ответов 7
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Как правильно реализовать интерфейс, что бы все методы были публичные и доступны через объект?
На примере строки 41 покажите правильную реализацию.

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
using System;
using System.ComponentModel;
using System.Collections.Generic;
 
namespace Application
{
    public class BindList<T> : IList<T>
    {
        private List<T> _list;
 
        public event EventHandler AddingNew;
        public event EventHandler ListChanged;
        private void OnAddingNew (object sender, EventArgs e) {
            this.AddingNew(sender, e);
        }
        private void OnListChanged (object sender, EventArgs e) {
            this.ListChanged(sender, e);
        }
 
        private void _resetBindings () {
            this.AddingNew = null;
            this.AddingNew += delegate { };
            this.ListChanged = null;
            this.ListChanged += delegate { };
        }
 
        public BindList () {
            this._resetBindings();
            this._list = new List<T>();
        }
 
        public BindList (List<T> list) {
            this._resetBindings();
            this._list = new List<T>(list);
        }
 
 
        // Если public - Ошибка
        // public int IList<T>.IndexOf (T item) { ...
        int IList<T>.IndexOf (T item) {
            return this._list.IndexOf(item);
        }
 
        void IList<T>.Insert (int index, T item) {
            this.OnAddingNew(this, EventArgs.Empty);
            this._list.Insert(index, item);
        }
 
        void IList<T>.RemoveAt (int index) {
            this.OnListChanged(this, EventArgs.Empty);
            this._list.RemoveAt(index);
        }
 
        T IList<T>.this[int index] {
            get {
                return this._list[index];
            }
            set {
                this.OnListChanged(this, EventArgs.Empty);
                this._list[index] = value;
            }
        }
 
        void ICollection<T>.Add (T item) {
            this.OnAddingNew(this, EventArgs.Empty);
            this._list.Add(item);
        }
 
        void ICollection<T>.Clear () {
            this.OnListChanged(this, EventArgs.Empty);
            this._list.Clear();
        }
 
        bool ICollection<T>.Contains (T item) {
            return this._list.Contains(item);
        }
 
        void ICollection<T>.CopyTo (T[] array, int arrayIndex) {
            this._list.CopyTo(array, arrayIndex);
        }
 
        int ICollection<T>.Count {
            get { return this._list.Count; }
        }
 
        bool ICollection<T>.IsReadOnly {
            get { return false; }
        }
 
        bool ICollection<T>.Remove (T item) {
            this.OnListChanged(this, EventArgs.Empty);
            return this._list.Remove(item);
        }
 
        IEnumerator<T> IEnumerable<T>.GetEnumerator () {
            return this._list.GetEnumerator();
        }
 
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () {
            return this._list.GetEnumerator();
        }
    }
 
    static class Program
    {
        
        static void Main () {
            BindList<int> bList = new BindList<int>();
            
        }
    }
}
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
15.12.2013, 21:29
Ответы с готовыми решениями:

Модификаторы доступа public, private, protected
Есть ли в Си модификаторы доступа public, private, protected?

Как не писать каждый раз public модификаторы в XAML?
Сейчас я делаю так: &lt;UserControl ... &lt;Grid... &lt;TextBlock Height=&quot;30&quot; x:FieldModifier=&quot;public&quot; ... ...

Изменить модификаторы доступа public к полям класса на private
Был тут вот такой код: namespace ConsoleApplication3 { class Room { public double length; //длина ...

7
438 / 362 / 100
Регистрация: 29.06.2010
Сообщений: 981
Записей в блоге: 1
15.12.2013, 21:32
В чем проблема, часть можете сделать public

Кликните здесь для просмотра всего текста
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
using System;
using System.ComponentModel;
using System.Collections.Generic;
 
namespace Application
{
    public class BindList<T> : IList<T>
    {
        private List<T> _list;
 
        public event EventHandler AddingNew;
        public event EventHandler ListChanged;
        private void OnAddingNew(object sender, EventArgs e)
        {
            this.AddingNew(sender, e);
        }
        private void OnListChanged(object sender, EventArgs e)
        {
            this.ListChanged(sender, e);
        }
 
        private void _resetBindings()
        {
            this.AddingNew = null;
            this.AddingNew += delegate { };
            this.ListChanged = null;
            this.ListChanged += delegate { };
        }
 
        public BindList()
        {
            this._resetBindings();
            this._list = new List<T>();
        }
 
        public BindList(List<T> list)
        {
            this._resetBindings();
            this._list = new List<T>(list);
        }
 
 
        // Если public - Ошибка
        // public int IList<T>.IndexOf (T item) { ...
        public int IndexOf(T item)
        {
            return this._list.IndexOf(item);
        }
 
        void IList<T>.Insert(int index, T item)
        {
            this.OnAddingNew(this, EventArgs.Empty);
            this._list.Insert(index, item);
        }
 
        void IList<T>.RemoveAt(int index)
        {
            this.OnListChanged(this, EventArgs.Empty);
            this._list.RemoveAt(index);
        }
 
        T IList<T>.this[int index]
        {
            get
            {
                return this._list[index];
            }
            set
            {
                this.OnListChanged(this, EventArgs.Empty);
                this._list[index] = value;
            }
        }
 
        void ICollection<T>.Add(T item)
        {
            this.OnAddingNew(this, EventArgs.Empty);
            this._list.Add(item);
        }
 
        void ICollection<T>.Clear()
        {
            this.OnListChanged(this, EventArgs.Empty);
            this._list.Clear();
        }
 
        bool ICollection<T>.Contains(T item)
        {
            return this._list.Contains(item);
        }
 
        void ICollection<T>.CopyTo(T[] array, int arrayIndex)
        {
            this._list.CopyTo(array, arrayIndex);
        }
 
        public int Count
        {
            get { return this._list.Count; }
        }
 
        public bool IsReadOnly
        {
            get { return false; }
        }
 
        public bool Remove(T item)
        {
            this.OnListChanged(this, EventArgs.Empty);
            return this._list.Remove(item);
        }
 
        public IEnumerator<T> GetEnumerator()
        {
            return this._list.GetEnumerator();
        }
 
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this._list.GetEnumerator();
        }
    }
 
    static class Program
    {
 
        static void Main()
        {
            BindList<int> bList = new BindList<int>();
 
        }
    }
}


Добавлено через 1 минуту
Цитата Сообщение от supra7sky Посмотреть сообщение
// public int IList<T>.IndexOf (T item) { ...
Что за ошибка?
1
 Аватар для supra7sky
15 / 15 / 5
Регистрация: 07.02.2013
Сообщений: 123
15.12.2013, 21:35  [ТС]
Цитата Сообщение от Grishaco Посмотреть сообщение
В чем проблема, часть можете сделать public

Кликните здесь для просмотра всего текста
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
using System;
using System.ComponentModel;
using System.Collections.Generic;
 
namespace Application
{
    public class BindList<T> : IList<T>
    {
        private List<T> _list;
 
        public event EventHandler AddingNew;
        public event EventHandler ListChanged;
        private void OnAddingNew(object sender, EventArgs e)
        {
            this.AddingNew(sender, e);
        }
        private void OnListChanged(object sender, EventArgs e)
        {
            this.ListChanged(sender, e);
        }
 
        private void _resetBindings()
        {
            this.AddingNew = null;
            this.AddingNew += delegate { };
            this.ListChanged = null;
            this.ListChanged += delegate { };
        }
 
        public BindList()
        {
            this._resetBindings();
            this._list = new List<T>();
        }
 
        public BindList(List<T> list)
        {
            this._resetBindings();
            this._list = new List<T>(list);
        }
 
 
        // Если public - Ошибка
        // public int IList<T>.IndexOf (T item) { ...
        public int IndexOf(T item)
        {
            return this._list.IndexOf(item);
        }
 
        void IList<T>.Insert(int index, T item)
        {
            this.OnAddingNew(this, EventArgs.Empty);
            this._list.Insert(index, item);
        }
 
        void IList<T>.RemoveAt(int index)
        {
            this.OnListChanged(this, EventArgs.Empty);
            this._list.RemoveAt(index);
        }
 
        T IList<T>.this[int index]
        {
            get
            {
                return this._list[index];
            }
            set
            {
                this.OnListChanged(this, EventArgs.Empty);
                this._list[index] = value;
            }
        }
 
        void ICollection<T>.Add(T item)
        {
            this.OnAddingNew(this, EventArgs.Empty);
            this._list.Add(item);
        }
 
        void ICollection<T>.Clear()
        {
            this.OnListChanged(this, EventArgs.Empty);
            this._list.Clear();
        }
 
        bool ICollection<T>.Contains(T item)
        {
            return this._list.Contains(item);
        }
 
        void ICollection<T>.CopyTo(T[] array, int arrayIndex)
        {
            this._list.CopyTo(array, arrayIndex);
        }
 
        public int Count
        {
            get { return this._list.Count; }
        }
 
        public bool IsReadOnly
        {
            get { return false; }
        }
 
        public bool Remove(T item)
        {
            this.OnListChanged(this, EventArgs.Empty);
            return this._list.Remove(item);
        }
 
        public IEnumerator<T> GetEnumerator()
        {
            return this._list.GetEnumerator();
        }
 
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this._list.GetEnumerator();
        }
    }
 
    static class Program
    {
 
        static void Main()
        {
            BindList<int> bList = new BindList<int>();
 
        }
    }
}


Добавлено через 1 минуту


Что за ошибка?
ошибка CS0106: Модификатор "public" недопустим для этого элемента
0
438 / 362 / 100
Регистрация: 29.06.2010
Сообщений: 981
Записей в блоге: 1
15.12.2013, 21:37
Цитата Сообщение от supra7sky Посмотреть сообщение
ошибка CS0106: Модификатор "public" недопустим для этого элемента
Я скинул вам рабочий код, скиньте свой в котором есть ошибка.
1
 Аватар для supra7sky
15 / 15 / 5
Регистрация: 07.02.2013
Сообщений: 123
15.12.2013, 21:43  [ТС]
Цитата Сообщение от Grishaco Посмотреть сообщение
Я скинул вам рабочий код, скиньте свой в котором есть ошибка.
Кликните здесь для просмотра всего текста
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
using System;
using System.ComponentModel;
using System.Collections.Generic;
 
namespace Application
{
    public class BindList<T> : IList<T>
    {
        private List<T> _list;
 
        public event EventHandler AddingNew;
        public event EventHandler ListChanged;
        private void OnAddingNew (object sender, EventArgs e) {
            this.AddingNew(sender, e);
        }
        private void OnListChanged (object sender, EventArgs e) {
            this.ListChanged(sender, e);
        }
 
        private void _resetBindings () {
            this.AddingNew = null;
            this.AddingNew += delegate { };
            this.ListChanged = null;
            this.ListChanged += delegate { };
        }
 
        public BindList () {
            this._resetBindings();
            this._list = new List<T>();
        }
 
        public BindList (List<T> list) {
            this._resetBindings();
            this._list = new List<T>(list);
        }
 
 
        // Если public - Ошибка
        // public int IList<T>.IndexOf (T item) { ...
        public int IList<T>.IndexOf (T item) {
            return this._list.IndexOf(item);
        }
 
        public void IList<T>.Insert (int index, T item) {
            this.OnAddingNew(this, EventArgs.Empty);
            this._list.Insert(index, item);
        }
 
        void IList<T>.RemoveAt (int index) {
            this.OnListChanged(this, EventArgs.Empty);
            this._list.RemoveAt(index);
        }
 
        T IList<T>.this[int index] {
            get {
                return this._list[index];
            }
            set {
                this.OnListChanged(this, EventArgs.Empty);
                this._list[index] = value;
            }
        }
 
        void ICollection<T>.Add (T item) {
            this.OnAddingNew(this, EventArgs.Empty);
            this._list.Add(item);
        }
 
        void ICollection<T>.Clear () {
            this.OnListChanged(this, EventArgs.Empty);
            this._list.Clear();
        }
 
        bool ICollection<T>.Contains (T item) {
            return this._list.Contains(item);
        }
 
        void ICollection<T>.CopyTo (T[] array, int arrayIndex) {
            this._list.CopyTo(array, arrayIndex);
        }
 
        int ICollection<T>.Count {
            get { return this._list.Count; }
        }
 
        bool ICollection<T>.IsReadOnly {
            get { return false; }
        }
 
        bool ICollection<T>.Remove (T item) {
            this.OnListChanged(this, EventArgs.Empty);
            return this._list.Remove(item);
        }
 
        IEnumerator<T> IEnumerable<T>.GetEnumerator () {
            return this._list.GetEnumerator();
        }
 
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () {
            return this._list.GetEnumerator();
        }
    }
 
    static class Program
    {
 
        static void Main () {
            BindList<int> bList = new BindList<int>();
 
        }
    }
}
Миниатюры
Не реализуется интерфейс IList<T>. Не позволяет использовать модификаторы public  
0
438 / 362 / 100
Регистрация: 29.06.2010
Сообщений: 981
Записей в блоге: 1
15.12.2013, 21:49
Уберите интерфейс IList<T>

C#
1
public int IList<T>.IndexOf(T item)
C#
1
public int IndexOf(T item)
Добавлено через 4 минуты
В общем попробую объяснить есть открытая и закрытая реализация интерфейсов. Для чего это нужно, например у вас есть два интерфейса с одинаковой сигнатурой метода и необходимо реализовать ее в классе, существует как минимум 4 имплементации интерфейсов.

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
public interface I1
        {
            void A();
        }
 
        public interface I2
        {
            void A();
        }
 
        public class A1 : I1, I2
        {
            void I1.A()
            {
            }
 
            void I2.A()
            {
            }
        }
 
        public class A2 : I1, I2
        {
            public void A()
            {
            }
 
            void I2.A()
            {
            }
        }
 
        public class A3 : I1, I2
        {
            void I1.A()
            {
            }
 
            public void A()
            {
            }
        }
 
        public class A4 : I1, I2
        {
            public void A()
            {
            }
        }
Так вот при разной реализации может меняться поведение программы.
1
 Аватар для supra7sky
15 / 15 / 5
Регистрация: 07.02.2013
Сообщений: 123
15.12.2013, 21:52  [ТС]
Все понял) Спасибо.
0
Master of Orion
Эксперт .NET
 Аватар для Psilon
6102 / 4958 / 905
Регистрация: 10.07.2011
Сообщений: 14,522
Записей в блоге: 5
16.12.2013, 00:50
supra7sky, как сказали выше, при явной реализации интерфейса не разрешается указывать модификатор, т.к. он может быть только public. Чтобы избежать путаницы и писанины, компилятор в принципе запрещает указывать модификатор.
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
16.12.2013, 00:50
Помогаю со студенческими работами здесь

Для чего нужны модификаторы protected, private, public
подскажите, кто в курсе, зачем вообще нужны эти модификаторы доступа? ведь, все их можно обойти... сейчас курю Страуструпа &quot;Дизайн...

Описать интерфейс IList
есть вот такое задание: Описать интерфейс IList, который объявляет операции хранения элементов в списке: добавить, удалить, вставить,...

Не определяется интерфейс IList<T>
Реализую интерфейс IList в своем классе. public class ListDinamic&lt;T&gt;:IList&lt;T&gt; А потом пытаюсь назначить листбоксу источник данных и...

Как реализовать интерфейс IList<object> в данном случае
Как реализовать IList&lt;object&gt;, что хранила бы объекты в БД. Объекты коллекции должны подгружаться в память при первом обращении к ним. ...

Нужно ли использовать использовать модификаторы доступа?
Добрый день. Поясните пожалуйста нужно ли использовать модификаторы доступа в проекте, если я являюсь его единственным программистом, то...


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

Или воспользуйтесь поиском по форуму:
8
Ответ Создать тему
Новые блоги и статьи
Автозаполнение реквизита при выборе элемента справочника
Maks 27.03.2026
Программный код из решения ниже на примере нетипового документа "ЗаявкаНаРемонтСпецтехники" разработанного в конфигурации КА2. При выборе "Спецтехники" (Тип Справочник. Спецтехника), заполняется. . .
Сумматор с применением элементов трёх состояний.
Hrethgir 26.03.2026
Тут. https:/ / fips. ru/ EGD/ ab3c85c8-836d-4866-871b-c2f0c5d77fbc Первый документ красиво выглядит, но без схемы. Это конечно не даёт никаких плюсов автору, но тем не менее. . . всё может быть. . .
Автозаполнение реквизитов при создании документа
Maks 26.03.2026
Программный код из решения ниже размещается в модуле объекта документа, в процедуре "ПриСозданииНаСервере". Алгоритм проверки заполнения реализован для исключения перезаписи значения реквизита,. . .
Команды формы и диалоговое окно
Maks 26.03.2026
1. Команда формы "ЗаполнитьЗапчасти". Программный код из решения ниже на примере нетипового документа "ЗаявкаНаРемонтСпецтехники" разработанного в конфигурации КА2. В качестве источника данных. . .
Кому нужен AOT?
DevAlt 26.03.2026
Решил сделать простой ланчер Написал заготовку: dotnet new console --aot -o UrlHandler var items = args. Split(":"); var tag = items; var id = items; var executable = args;. . .
Отправка уведомления на почту при изменении наименования справочника
Maks 24.03.2026
Программная отправка письма электронной почты на примере изменения наименования типового справочника "Склады" в конфигурации БП3. Перед реализацией необходимо выполнить настройку системной учетной. . .
модель ЗдравоСохранения 5. Меньше увольнений- больше дохода!
anaschu 24.03.2026
Теперь система здравосохранения уменьшает количество увольнений. 9TO2GP2bpX4 a42b81fb172ffc12ca589c7898261ccb/ https:/ / rutube. ru/ video/ a42b81fb172ffc12ca589c7898261ccb/ Слева синяя линия -. . .
Midnight Chicago Blues
kumehtar 24.03.2026
Такой Midnight Chicago Blues, знаешь?. . Когда вечерние улицы становятся ночными, а ты не можешь уснуть. Ты идёшь в любимый старый бар, и бармен наливает тебе виски. Ты смотришь на пролетающие. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru