Форум программистов, компьютерный форум, киберфорум
Visual Basic
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.93/15: Рейтинг темы: голосов - 15, средняя оценка - 4.93
0 / 0 / 0
Регистрация: 16.08.2007
Сообщений: 145

Как задать значение по умолчанию для свойства класса

20.02.2008, 15:17. Показов 3271. Ответов 6
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Где и как можно сохранять и считывать значения свойств класса. Помню - такая возможность есть - но нет книжки под рукой
Заранее благодарен
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
20.02.2008, 15:17
Ответы с готовыми решениями:

Как установить свойство по умолчанию для своего класса
Как установить свойство по умолчанию для своего класса

Явно задать значение свойства одному из полей класса
Здравствуйте, подскажите почему c# ругается? Есть класс: public class BinaryTree{ public BinaryTree left; public...

Как задать значение по умолчанию для переменной заданной макросом AC_SUBST()?
Макрос AC_CHECK_LIB() по умолчанию ищет библиотеки в папке /usr/bin/. Как установить свой путь для поиска библиотек? Добавлено через...

6
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
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
20.02.2008, 19:10
Помогаю со студенческими работами здесь

Задать значение по умолчанию для ComboBox
Я создаю динамически DataGridView, в нем делаю несколько колонок типа DataGridViewComboBoxColumn. А теперь непонятно, как обратиться к...

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

Как сделать значение по умолчанию для параметра, если оно должно быть значением по умолчанию для типа T?
Как сделать значение по умолчанию для параметра, если оно должно быть значением по умолчанию для типа T? Module Program Sub Method(Of...

Как задать каждому элементу массива значение по умолчанию?
Например я знаю что void max(int t=9){//значение по умолчанию переменой t++; } А как такую штуку сделать для каждого елемента...

Значение свойства по умолчанию
Есть ли возможность заставить Builder-6 по умолчанию давать те значения свойств, которые мне больше нравятся? Пытался (по-хамски): залез...


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

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Первый деплой
lagorue 16.01.2026
Не спеша развернул своё 1ое приложение в kubernetes. А дальше мне интересно создать 1фронтэнд приложения и 2 бэкэнд приложения развернуть 2 деплоя в кубере получится 2 сервиса и что-бы они. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит: токи, напряжения и их 1 и 2 производные при t = 0;. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Изучаю kubernetes
lagorue 13.01.2026
А пригодятся-ли мне знания kubernetes в России?
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru