|
0 / 0 / 0
Регистрация: 16.08.2007
Сообщений: 145
|
|
Как задать значение по умолчанию для свойства класса20.02.2008, 15:17. Показов 3293. Ответов 6
Метки нет (Все метки)
Где и как можно сохранять и считывать значения свойств класса. Помню - такая возможность есть - но нет книжки под рукой
Заранее благодарен
0
|
|
| 20.02.2008, 15:17 | |
|
Ответы с готовыми решениями:
6
Как установить свойство по умолчанию для своего класса Явно задать значение свойства одному из полей класса Как задать значение по умолчанию для переменной заданной макросом AC_SUBST()? |
|
eddy
|
|
| 20.02.2008, 15:47 | |
|
Открыть меню Tools/Procedure Attributes.
Нажать кнопку Advanced и в поле Procedure ID выбрать опцию (Default). |
|
|
0 / 0 / 0
Регистрация: 16.08.2007
Сообщений: 145
|
|
| 20.02.2008, 16:03 [ТС] | |
|
Насколько я понимаю с помощью этих действий можно само свойство сделать Default, те При обращении к объекту напрямую без указания свойства программа будет обращаться к нему те напр
dim text1 as textbox strVar = Text1 ' здесь Default - свойство - текст Меня же интересует как свойству задать значение по умолчанию и/или как в собственном классе закодировать запись значения свойства так чтобы это значение хранилось и после удаления объекта из памяти, а потом, при следующем вызове присваивалось соответствующему свойству Там что-то вроде Init/Read/Write Properties
0
|
|
|
eddy
|
|
| 20.02.2008, 16:16 | |
|
'// Вот кусок работающего кода, например, для свойства Caption по умолчанию будет 'Hyperlink Demo'
Private Sub UserControl_WriteProperties(PropBag As PropertyBag) Call PropBag.WriteProperty('Enabled', lblHyperlink.Enabled, True) Call PropBag.WriteProperty('Font', lblHyperlink.Font, Ambient.Font) Call PropBag.WriteProperty('Caption', lblHyperlink.Caption, 'Hyperlink Demo') Call PropBag.WriteProperty('Alignment', lblHyperlink.Alignment, 0) Call PropBag.WriteProperty('AutoSize', lblHyperlink.AutoSize, True) Call PropBag.WriteProperty('HoverColor', m_HoverColor, m_def_HoverColor) Call PropBag.WriteProperty('HyperLink', m_HyperLink, m_def_HyperLink) Call PropBag.WriteProperty('Appearance', lblHyperlink.Appearance, 1) Call PropBag.WriteProperty('BorderStyle', lblHyperlink.BorderStyle, 0) Call PropBag.WriteProperty('ForeColor', lblHyperlink.ForeColor, &H404040) Call PropBag.WriteProperty('BackColor', lblHyperlink.BackColor, &H8000000F) Call PropBag.WriteProperty('AutoToolTip', m_AutoToolTip, m_def_AutoToolTip) Call PropBag.WriteProperty('SoundOn', m_SoundOn, m_def_SoundOn) Call PropBag.WriteProperty('SoundID', m_SoundID, m_def_SoundID) Call PropBag.WriteProperty('MOUnderline', m_MOUnderline, m_def_MOUnderline) Call PropBag.WriteProperty('MOPointer', m_MOPointer, m_def_MOPointer) End Sub |
|
|
0 / 0 / 1
Регистрация: 23.01.2008
Сообщений: 251
|
|
| 20.02.2008, 16:18 | |
|
юзай Class_Initialize & Class_Terminate
0
|
|
|
0 / 0 / 0
Регистрация: 17.08.2007
Сообщений: 539
|
|
| 20.02.2008, 16:38 | |
|
Вообще то, по рекомендациям Старшего Брата, свойства и прочие торчащие палки классов лучше сохранять в БД. Но в виду отсутствия книги под рукой держи: :-)
Persisting a Component's Data Most components have properties; in most cases you'll want to establish default values for those properties in the Initialize event of the class. Those default values are frozen when you compile the component, so how do you allow a developer to change the default values to meet their own special conditions? Classes have a special property, Persistable, that allow you to store a component's values between instances. Suppose that you had an ActiveX DLL that calculates loans, with an InterestRate property used in the calculations. You could initialize the InterestRate to some arbitrary value, but since interest rates periodically go up or down, the InterestRate property would need to be modified each time the component is run. With class persistence, you can store the InterestRate value and modify it only when the interest rate changes. Each time your component is run it can retrieve the InterestRate from storage, so the component will always provide the latest rate. While ActiveX controls have always been able to persist their data; persistence for ActiveX components is slightly different. A control stores property settings inside it's .cls file, but a component can't do that. Instead, it uses a PropertyBag object that can be saved just about anywhere – in a file, a database, a cell in a spreadsheet, or even in the registry. For More Information To learn more about persisting ActiveX controls, see 'Saving the Properties of a Control,' in Chapter 9, 'Building an ActiveX Control'.see 'Saving the Properties of a Control,' in 'Building an ActiveX Control'. Setting Up Class Persistence In order to be persistable, a class must meet two conditions: it must be public and creatable. If you think about, this makes sense – after all, persistence wouldn't be useful in a private component. If a class meets both conditions, the Persistable property appears in the Properties window. By default, the Persistable property is set to 0 (NotPersistable). By changing this value to 1 (Persistable), three new events are added to the class: ReadProperties, WriteProperties, and InitProperties. As you might guess, these events are use to read, write, and initialize the class's properties. Persisting a Property You can mark a property as persistable by implementing the PropertyChanged method in a Property Let or Property Set procedure, as in the following example: Private mInterestRate As Single Public Property Let InterestRate(newRate As Single) mInterestRate = newRate PropertyChanged 'InterestRate' End Sub Calling the PropertyChanged method marks the InterestRate property as dirty. The WriteProperties event will fire when the class is terminated if any property in the class has called PropertyChanged. The ReadProperties, WriteProperties and InitProperties Events The WriteProperties event procedure is used when a class is terminating to write the current property values to a private storage known as a PropertyBag object. The following code is used to save a property to the built-in PropertyBag: Private Sub Class_WriteProperties(PropBag As PropertyBag) PropBag.WriteProperty 'InterestRate', mInterestRate, conDefaultRate End Sub The Property Bag's WriteProperty method in the above code takes three arguments: the name of the property to save ('InterestRate'), the value to save (mInterestRate), and a default value (DefaultRate). If the new value matches the constant conDefaultRate, ly take an object created in one place and reuse it in another, complete with its data? Well, not exactly. The original object is long gone. What you are passing in a PropertyBag is an exact copy of the object, not the object itself. This ability to 'clone' an object for reuse is a powerful concept, especially when it comes to designing workflow applications. Удачи!
0
|
|
|
0 / 0 / 0
Регистрация: 16.08.2007
Сообщений: 145
|
|
| 20.02.2008, 19:10 [ТС] | |
|
Спасибо всем!
0
|
|
| 20.02.2008, 19:10 | |
|
Помогаю со студенческими работами здесь
7
Задать значение по умолчанию для ComboBox
Как задать каждому элементу массива значение по умолчанию? Значение свойства по умолчанию Искать еще темы с ответами Или воспользуйтесь поиском по форуму: |
|
Новые блоги и статьи
|
|||
|
Жизнь в неопределённости
kumehtar 23.03.2026
Жизнь — это постоянное существование в неопределённости. Например, даже если у тебя есть список дел, невозможно дойти до точки, где всё окончательно завершено и больше ничего не осталось. В принципе,. . .
|
Модель здравоСохранения: работники работают быстрее после её введения.
anaschu 23.03.2026
geJalZw1fLo
Корпорация до введения программа здравоохранения имела много невыполненных работниками заданий, после введения программы количество заданий выросло.
Но на выплатах по больничным это. . .
|
1С: Контроль уникальности заводского номера
Maks 23.03.2026
Алгоритм контроля уникальности заводского (или серийного) номера на примере документа выдачи шин для спецтехники с табличной частью. Данные берутся из регистра сведений, по которому настроено. . .
|
Хочу заставить корпорации вкладываться в здоровье сотрудников: делаю мат модель здравосохранения
anaschu 22.03.2026
e7EYtONaj8Y
Z4Tv2zpXVVo
https:/ / github. com/ shumilovas/ med2. git
|
|
1С: Программный отбор элементов справочника по группе
Maks 22.03.2026
Установка программного отбора элементов справочника "Номенклатура" из модуля формы документа.
В качестве фильтра для отбора справочника служит группа номенклатуры.
Отбор по наименованию группы. . .
|
Как я обхитрил таблицу Word
Alexander-7 21.03.2026
Когда мигает курсор у внешнего края таблицы, и нам надо перейти на новую строку, а при нажатии Enter создается новый ряд таблицы с ячейками, то мы вместо нервных нажатий Энтеров мы пишем любые буквы. . .
|
Krabik - рыболовный бот для WoW 3.3.5a
AmbA 21.03.2026
без регистрации и смс.
Это не торговля, приложение не содержит рекламы. Выполняет свою непосредственную задачу - автоматизацию рыбалки в WoW - и ничего более. Однако если админы будут против -. . .
|
1С: Программный отбор элементов справочника по значению перечисления
Maks 21.03.2026
Установка программного отбора элементов справочника "Сотрудники" из модуля формы документа.
В качестве фильтра для отбора служит значение перечислений.
/ / Событие "НачалоВыбора" реквизита на форме. . .
|