powered by simpleCommunicator - 2.0.56     © 2025 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Virtual member call in constructor
3 сообщений из 3, страница 1 из 1
Virtual member call in constructor
    #38248848
Фотография Mikhail Tchervonenko
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Доброе время суток!

Если я вызываю в конструкторе формы напр. докание:
this.Dock = DockStyle.Left;
это вызывает предупреждение "Virtual member call in constructor".
Хоть это и работает вопрос:
Если мне надо изначально установить какое то свойство в наследуемомо классе которое уже существует в материнском классе как это правильно сделать?

Спасибо.
...
Рейтинг: 0 / 0
Virtual member call in constructor
    #38248879
LameUser
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Mikhail TchervonenkoДоброе время суток!

Если я вызываю в конструкторе формы напр. докание:
this.Dock = DockStyle.Left;
это вызывает предупреждение "Virtual member call in constructor".
Хоть это и работает вопрос:
Если мне надо изначально установить какое то свойство в наследуемомо классе которое уже существует в материнском классе как это правильно сделать?

Спасибо.

тынц


When an object written in C# is constructed, what happens is that the initializers run in order from the most derived class to the base class, and then constructors run in order from the base class to the most derived class (see Eric Lippert's blog for details as to why this is).

Also in .NET objects do not change type as they are constructed, but start out as the most derived type, with the method table being for the most derived type. This means that virtual method calls always run on the most derived type.

When you combine these two facts you are left with the problem that if you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, that it will be called on a class whose constructor has not been run, and therefore may not be in a suitable state to have that method called.

This problem is, of course, mitigated if you mark your class as sealed to ensure that it is the most derived type in the inheritance hierarchy - in which case it is perfectly safe to call the virtual method.

You have to seal either class or virtual member.


Надеюсь с английским нет проблем :)
...
Рейтинг: 0 / 0
Virtual member call in constructor
    #38249125
bazile
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Mikhail Tchervonenko, "Virtual member call in constructor" предупреждает о возможной проблеме которая может возникнуть если текущий класс или его наследник переопределят этот виртуальный член. В таком случае _могут_ возникнуть проблемы связанные с порядком вызовов конструкторов:
Код: 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.
public class Base
{
    protected int item;

    protected Base()
    {
        VirtualFunc();                            
    }

    public virtual void VirtualFunc()
    {
        Console.WriteLine(item);
    }

}

public class Derived : Base
{
    public Derived()
    {
        item = 1;

        VirtualFunc();
    }

    public override void VirtualFunc()
    {
        if (item != 1)
        {
            throw new Exception("Should never do this");
        }
    }
}



В твоем случае предупржедение можно игнорировать т.к. маловероятно что ты планируешь переопределять свойство Dock.
...
Рейтинг: 0 / 0
3 сообщений из 3, страница 1 из 1
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Virtual member call in constructor
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]