ref/packages [ru]
Differences between version #10077 and #10085
1c1
< Each file can contain several //classes//, //enums// and //imports//. They are all part of the //package// declared at the beginning of the file. If //package// is not declared then the default empty package is used. Each //type// has then a //path// corresponding to the //package// name followed by the //type// name.
---
> Каждый файл может содержать классы (classes), перечисления (enums) и операторы импорта (imports). Все они являются частью пакета (package) и объявляются в начале класса. Если пакет не указан, то по-умолчанию будет использован пустой пакет. Каждый тип (type) имеет путь (path), который состоит из имени пакета, в котором находится тип и, собственно, имени этого типа.
3d2
< <code haxe>
12,14c11
< </code>
<
< This file declares two //types// : ''my.pack.E'' and ''my.pack.C''. It's possible to have several classes in the same file, but the type name must be //unique// in the whole application, so conflicts can appear if you're not using packages enough (this does not mean that you have to use long packages names everywhere).
---
> В примере выше объявлены два типа : my.pack.E и my.pack.C. Можно объявлять несколько классов в одном и том же файле, но их имена (с названием пакета) должны быть уникальны в пределах приложения, поэтому при неправильном использовании пакетов могут возникнуть конфликты (что, тем не менее, не обязывает вас использовать длинные названия пакетов везде).
16c13
< When creating types using packages, you should create a nested folder/directory structure matching the package name, and your files defining the type should be created in the innermost folder/directory. The name of the file should generally match the type you are creating. For example, to create the types E and C, in the package //my.pack// as shown above, your folder structure should be //my\pack// and the files could be //E.hx// and //C.hx// in the folder //pack//. In general, the name of the file is the one containing the definition of the main //class//.
---
> При использовании пакетов файлы должны быть помещены в подпапки, имена которых должны совпадать с именами пакетов. Называть файл принято так же как и основной класс, который в нем определён.
18c15
< The file extension for **Haxe** is ''.hx''.
---
> Расширение Haxe файлов — .hx.
20c17
< Each part of the path in package names must begin with a lower case letter and, like all types, type names in packages must begin with an upper case letter. Hence ''My.Pack'' is an invalid package, as is ''my.Pack''. Similarly, ''my.pack.e'' would not be a valid type name or import.
---
> Название пакета должно начинаться с маленькой буквы, а название типа (и соответственно название файла, прим. пер.) должно начинаться с большой. Таким образом, название пакета My.Pack не корректно, также как и my.Pack. Некорректным, так же, будет и название типа my.pack.e.
22c19,20
< ====== Imports ======
---
> Операторы импорта (Imports)
> Операторы импорта могут использоваться для доступа ко всем типам в файле без явного указания имени пакета.
24c22
< Imports can be used to have access to all the types of a file without needing to specify the package name.
---
> Запись:
26d23
< <code haxe>
30,32c27
< </code>
<
< Is identical to the following :
---
> эквивалентна:
34d28
< <code haxe>
40,101c34
< </code>
<
< The only difference is that when using import you can use //enum constructors// that were declared in the ''my/pack/C.hx'' file.
<
< ==== Applying additional static methods to class instances ====
< The //using// keyword imports a file, additionally applying all static methods from that file as member functions on the type of their first parameter.
<
< Say we have:
< <code haxe>
< package my.pack;
< class StringUtils {
< public static function double( string:String ):String {
< return string + string;
< }
< }
< </code>
<
< Then one could import the class and double a string:
< <code haxe>
< import my.pack.StringUtils;
<
< StringUtils.double( "Hello!"); // returns "Hello!Hello!"
< </code>
<
< Or, equivalently:
< <code haxe>
< using my.pack.StringUtils;
<
< "Hello!".double(); // returns "Hello!Hello!"
< </code>
<
< ==== Importing a single type from a module ====
< Given a module containing multiple types, such as
< <code haxe>
< package my.pack2;
< typedef A = { a : String }
< typedef B = { b : String }
< </code>it is possible to import one type at a time from that module, using the following syntax:
< <code haxe>
< import my.pack2.A;
< </code>
<
< ==== Importing using wildcards ('*') ====
<
< Importing multiple types with wildcards is NOT supported in Haxe, i.e.
<
< <code>
< import flash.display.*;
< </code>
<
< will result in compiler error, quote "x.hx:1: characters x-x : Unexpected *".
<
<
< ====== Type Lookup ======
<
< When a type name is found, the following lookup is performed, in this order:
<
< * current class type parameters
< * standard types
< * types declared in the current file
< * types declared in imported files (if the searched package is empty)
< * if not found, the corresponding file is loaded and the type is searched inside it
---
> Разница лишь в том, что при использовании оператора импорта у вас появляется возможность использовать еще и перечисление, которое было объявлено в файле my/pack/C.hx (см. выше).
103c36,37
< ====== Enum Constructors ======
---
> Выявление типов
> Когда обнаружено имя типа, его определение ищется в следующем порядке:
105c39,45
< In order to use //enum// constructors, the file in which the //enum// is declared must first be imported, or you can use the full type path to access constructors as if they were static fields of the //enum// type.
---
> параметризующие типы текущего класса
> стандартные типы
> типы, объявленные в текущем файле
> типы, объявленные в импортируемых файлах (если в данном пакете объявление не найдено)
> если определение все еще не обнаружено, загружается соответствующий файл и тип ищется внутри него
> Конструкторы перечисления
> Для того, чтобы использовать конструкторы перечисления нужно импортировать файл в котором определено это перечисление, или же, можно использовать полный путь к конструкторам так, как если бы они были статическим полями перечисления.
107d46
< <code haxe>
109,113c48
< </code>
<
< As an exception, in ''switch'': if the type of the //enum// is known at compile time, then you can use constructors directly without the need to import.
<
< «« [[/ref/enums]] | [[/ref/dynamic]] »»
\ No newline at end of file
---
> Из этого правила есть исключение. В операторе switch, если тип перечисления известен во время компиляции, можно использовать конструкторы напрямую, без необходимости импорта.
\ No newline at end of file
| Ver | Date | User | Action |
|---|---|---|---|
| #12134 | 2012-01-05 13:56:58 | kakimakaki | View | Diff |
| #10181 | 2011-02-15 10:49:05 | Scythian | View | Diff |
| #10167 | 2011-02-11 12:48:48 | Scythian | View | Diff |
| #10166 | 2011-02-11 12:47:47 | Scythian | View | Diff |
| #10085 | 2011-02-01 17:21:27 | Scythian | View | Diff |
| #10077 | 2011-02-01 16:16:04 | Scythian | View | Diff |
| #10076 | 2011-02-01 16:16:04 | Scythian | Set title to Пакеты и импорт |
Previous | Next