- Names of Classes, Structs, and Interfaces
- Names of Generic Type Parameters
- Names of Common Types
- Naming Enumerations
- Window Classes (Windows and Messages)
- In This Section
- Window Class Functions
- Имена классов, структур и интерфейсов Names of Classes, Structs, and Interfaces
- Имена параметров универсального типа Names of Generic Type Parameters
- Имена общих типов Names of Common Types
- Перечисления именования Naming Enumerations
Names of Classes, Structs, and Interfaces
The naming guidelines that follow apply to general type naming.
вњ”пёЏ DO name classes and structs with nouns or noun phrases, using PascalCasing.
This distinguishes type names from methods, which are named with verb phrases.
вњ”пёЏ DO name interfaces with adjective phrases, or occasionally with nouns or noun phrases.
Nouns and noun phrases should be used rarely and they might indicate that the type should be an abstract class, and not an interface.
вќЊ DO NOT give class names a prefix (e.g., «C»).
вњ”пёЏ CONSIDER ending the name of derived classes with the name of the base class.
This is very readable and explains the relationship clearly. Some examples of this in code are: ArgumentOutOfRangeException , which is a kind of Exception , and SerializableAttribute , which is a kind of Attribute . However, it is important to use reasonable judgment in applying this guideline; for example, the Button class is a kind of Control event, although Control doesn’t appear in its name.
вњ”пёЏ DO prefix interface names with the letter I, to indicate that the type is an interface.
For example, IComponent (descriptive noun), ICustomAttributeProvider (noun phrase), and IPersistable (adjective) are appropriate interface names. As with other type names, avoid abbreviations.
вњ”пёЏ DO ensure that the names differ only by the «I» prefix on the interface name when you are defining a class–interface pair where the class is a standard implementation of the interface.
Names of Generic Type Parameters
Generics were added to .NET Framework 2.0. The feature introduced a new kind of identifier called type parameter.
вњ”пёЏ DO name generic type parameters with descriptive names unless a single-letter name is completely self-explanatory and a descriptive name would not add value.
вњ”пёЏ CONSIDER using T as the type parameter name for types with one single-letter type parameter.
вњ”пёЏ DO prefix descriptive type parameter names with T .
вњ”пёЏ CONSIDER indicating constraints placed on a type parameter in the name of the parameter.
For example, a parameter constrained to ISession might be called TSession .
Names of Common Types
вњ”пёЏ DO follow the guidelines described in the following table when naming types derived from or implementing certain .NET Framework types.
Base Type | Derived/Implementing Type Guideline |
---|---|
System.Attribute | вњ”пёЏ DO add the suffix «Attribute» to names of custom attribute classes. |
System.Delegate | вњ”пёЏ DO add the suffix «EventHandler» to names of delegates that are used in events. вњ”пёЏ DO add the suffix «Callback» to names of delegates other than those used as event handlers. вќЊ DO NOT add the suffix «Delegate» to a delegate. |
System.EventArgs | вњ”пёЏ DO add the suffix «EventArgs.» |
System.Enum | вќЊ DO NOT derive from this class; use the keyword supported by your language instead; for example, in C#, use the enum keyword. вќЊ DO NOT add the suffix «Enum» or «Flag.» |
System.Exception | вњ”пёЏ DO add the suffix «Exception.» |
IDictionary IDictionary | вњ”пёЏ DO add the suffix «Dictionary.» Note that IDictionary is a specific type of collection, but this guideline takes precedence over the more general collections guideline that follows. |
IEnumerable ICollection IList IEnumerable ICollection IList | вњ”пёЏ DO add the suffix «Collection.» |
System.IO.Stream | вњ”пёЏ DO add the suffix «Stream.» |
CodeAccessPermission IPermission | вњ”пёЏ DO add the suffix «Permission.» |
Naming Enumerations
Names of enumeration types (also called enums) in general should follow the standard type-naming rules (PascalCasing, etc.). However, there are additional guidelines that apply specifically to enums.
вњ”пёЏ DO use a singular type name for an enumeration unless its values are bit fields.
вњ”пёЏ DO use a plural type name for an enumeration with bit fields as values, also called flags enum.
вќЊ DO NOT use an «Enum» suffix in enum type names.
вќЊ DO NOT use «Flag» or «Flags» suffixes in enum type names.
вќЊ DO NOT use a prefix on enumeration value names (e.g., «ad» for ADO enums, «rtf» for rich text enums, etc.).
Portions В© 2005, 2009 Microsoft Corporation. All rights reserved.
Reprinted by permission of Pearson Education, Inc. from Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, 2nd Edition by Krzysztof Cwalina and Brad Abrams, published Oct 22, 2008 by Addison-Wesley Professional as part of the Microsoft Windows Development Series.
Window Classes (Windows and Messages)
This topic describes the types of window classes, how the system locates them, and the elements that define the default behavior of windows that belong to them.
A window class is a set of attributes that the system uses as a template to create a window. Every window is a member of a window class. All window classes are process specific.
In This Section
Name | Description |
---|---|
About Window Classes | Discusses window classes. Each window class has an associated window procedure shared by all windows of the same class. The window procedure processes messages for all windows of that class and therefore controls their behavior and appearance. |
Using Window Classes | Demonstrates how to register a local window and use it to create a main window. |
Window Class Reference | Contains the API reference. |
Window Class Functions
Name | Description |
---|---|
GetClassInfoEx | Retrieves information about a window class, including a handle to the small icon associated with the window class. The GetClassInfo function does not retrieve a handle to the small icon. |
GetClassLong | Retrieves the specified 32-bit (long) value from the WNDCLASSEX structure associated with the specified window. |
GetClassLongPtr | Retrieves the specified value from the WNDCLASSEX structure associated with the specified window. |
GetClassName | Retrieves the name of the class to which the specified window belongs. |
GetWindowLong | Retrieves information about the specified window. The function also retrieves the 32-bit (long) value at the specified offset into the extra window memory. |
GetWindowLongPtr | Retrieves information about the specified window. The function also retrieves the value at a specified offset into the extra window memory. |
RegisterClass | Registers a window class for subsequent use in calls to the CreateWindow or CreateWindowEx function. |
RegisterClassEx | Registers a window class for subsequent use in calls to the CreateWindow or CreateWindowEx function. |
SetClassLongPtr | Replaces the specified value at the specified offset in the extra class memory or the WNDCLASSEX structure for the class to which the specified window belongs. |
SetClassWord | Replaces the 16-bit (WORD) value at the specified offset into the extra class memory for the window class to which the specified window belongs. |
SetWindowLong | Changes an attribute of the specified window. The function also sets the 32-bit (long) value at the specified offset into the extra window memory. |
SetWindowLongPtr | Changes an attribute of the specified window. The function also sets a value at the specified offset in the extra window memory. |
UnregisterClass | Unregisters a window class, freeing the memory required for the class. |
The following functions are obsolete.
Name | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GetClassInfo | Retrieves information about a window class.
| ||||||||||||||||||||
GetClassWord | Retrieves the 16-bit (WORD) value at the specified offset into the extra class memory for the window class to which the specified window belongs.
| ||||||||||||||||||||
SetClassLong | Replaces the specified 32-bit (long) value at the specified offset into the extra class memory or the WNDCLASSEX structure for the class to which the specified window belongs.
Имена классов, структур и интерфейсов Names of Classes, Structs, and InterfacesПриведенные ниже рекомендации по именованию применяются к общему именованию типов. The naming guidelines that follow apply to general type naming. ✔️ имена классов и структур с существительными или субстантивные словосочетаниями с помощью Паскалкасинг. ✔️ DO name classes and structs with nouns or noun phrases, using PascalCasing. Это отличает имена типов от методов, названных с помощью фраз глагола. This distinguishes type names from methods, which are named with verb phrases. ✔️ ИСПОЛЬЗОВАТЬ именованные интерфейсы с фразами прилагательных или иногда с существительными или фразами с существительными. ✔️ DO name interfaces with adjective phrases, or occasionally with nouns or noun phrases. Существительные и фразы существительное следует использовать редко, и они могут указывать, что тип должен быть абстрактным классом, а не интерфейсом. Nouns and noun phrases should be used rarely and they might indicate that the type should be an abstract class, and not an interface. ❌ НЕ присваивайте имена классов префиксом (например, «C»). ❌ DO NOT give class names a prefix (e.g., «C»). ✔️ Рекомендуется завершать имена производных классов именем базового класса. ✔️ CONSIDER ending the name of derived classes with the name of the base class. Это очень понятное и понятное отношение. This is very readable and explains the relationship clearly. Вот несколько примеров этого кода: ArgumentOutOfRangeException , который является разновидностью Exception , и SerializableAttribute , которая является разновидностью Attribute . Some examples of this in code are: ArgumentOutOfRangeException , which is a kind of Exception , and SerializableAttribute , which is a kind of Attribute . Однако важно использовать разумные меры при применении этой рекомендации; Например, Button класс является разновидностью Control события, хотя Control не отображается в его имени. However, it is important to use reasonable judgment in applying this guideline; for example, the Button class is a kind of Control event, although Control doesn’t appear in its name. ✔️ префиксы имен интерфейсов с буквой I, чтобы указать, что тип является интерфейсом. ✔️ DO prefix interface names with the letter I, to indicate that the type is an interface. Например, IComponent (описательное существительное), ICustomAttributeProvider (субстантивные словосочетания) и IPersistable (прилагательное) — соответствующие имена интерфейсов. For example, IComponent (descriptive noun), ICustomAttributeProvider (noun phrase), and IPersistable (adjective) are appropriate interface names. Как и в случае с другими именами типов, следует избегать сокращений. As with other type names, avoid abbreviations. ✔️ Убедитесь, что имена отличаются только префиксом «I» в имени интерфейса при определении пары «класс — интерфейс», в которой класс является стандартной реализацией интерфейса. ✔️ DO ensure that the names differ only by the «I» prefix on the interface name when you are defining a class–interface pair where the class is a standard implementation of the interface. Имена параметров универсального типа Names of Generic Type ParametersУниверсальные шаблоны были добавлены в .NET Framework 2,0. Generics were added to .NET Framework 2.0. В этой функции появился новый тип идентификатора, называемый параметром типа. The feature introduced a new kind of identifier called type parameter. ✔️ имена параметров универсального типа с описательными именами, если только имя в одном письме не является полностью понятным, а описательное имя не будет добавлять значение. ✔️ DO name generic type parameters with descriptive names unless a single-letter name is completely self-explanatory and a descriptive name would not add value. ✔️ РЕКОМЕНДУЕТСЯ использовать T в качестве имени параметра типа для типов с одним однобуквенным параметром типа. ✔️ CONSIDER using T as the type parameter name for types with one single-letter type parameter. ✔️ добавлять в префикс имена параметров описательного типа с помощью T . ✔️ DO prefix descriptive type parameter names with T . ✔️ Рассмотрите возможность указания ограничений, накладываемых на параметр типа в имени параметра. ✔️ CONSIDER indicating constraints placed on a type parameter in the name of the parameter. Например, может быть вызван параметр с ограничением ISession TSession . For example, a parameter constrained to ISession might be called TSession . Имена общих типов Names of Common Types✔️ следовать рекомендациям, описанным в следующей таблице, при именовании типов, производных от или реализующих определенные типы .NET Framework. ✔️ DO follow the guidelines described in the following table when naming types derived from or implementing certain .NET Framework types.
Перечисления именования Naming EnumerationsИмена типов перечисления (также называемые перечислениями) в целом должны соответствовать стандартным правилам именования типов (Паскалкасинг и т. д.). Names of enumeration types (also called enums) in general should follow the standard type-naming rules (PascalCasing, etc.). Однако существуют дополнительные рекомендации, которые применяются специально для перечислений. However, there are additional guidelines that apply specifically to enums. ✔️ использовать единственное имя типа для перечисления, если его значения не являются битовыми полями. ✔️ DO use a singular type name for an enumeration unless its values are bit fields. ✔️ использовать имя типа во множественном числе для перечисления с битовыми полями в качестве значений, также называемых flags Enum. ✔️ DO use a plural type name for an enumeration with bit fields as values, also called flags enum. ❌ НЕ используйте суффикс «enum» в именах типов Enum. ❌ DO NOT use an «Enum» suffix in enum type names. ❌ НЕ используйте суффикс «Flag» или «Flags» в именах типов Enum. ❌ DO NOT use «Flag» or «Flags» suffixes in enum type names. ❌ НЕ используйте префикс для имен значений перечисления (например, «ad» для перечислений ADO, «RTF» для перечислений форматированного текста и т. д.). ❌ DO NOT use a prefix on enumeration value names (e.g., «ad» for ADO enums, «rtf» for rich text enums, etc.). Части © 2005, 2009 Корпорация Майкрософт. Все права защищены. Portions © 2005, 2009 Microsoft Corporation. All rights reserved. Перепечатано с разрешения Pearson Education, Inc. из книги Инфраструктура программных проектов. Соглашения, идиомы и шаблоны для многократно используемых библиотек .NET (2-е издание), авторы: Кржиштоф Цвалина (Krzysztof Cwalina) и Брэд Абрамс (Brad Abrams). Книга опубликована 22 октября 2008 г. издательством Addison-Wesley Professional в рамках серии, посвященной разработке для Microsoft Windows. Reprinted by permission of Pearson Education, Inc. from Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, 2nd Edition by Krzysztof Cwalina and Brad Abrams, published Oct 22, 2008 by Addison-Wesley Professional as part of the Microsoft Windows Development Series. |