- Управление версиями Versioning
- Критические изменения Breaking changes
- Номера версий Version numbers
- Версия пакета NuGet NuGet package version
- Версия сборки Assembly version
- Версия файла сборки Assembly file version
- Информационная версия сборки Assembly informational version
- Version Control window
- Title bar context menu and buttons
- Enable version control
- Associate a project root with a version control system
- Associate a directory with a version control system
- Manage unregistered directories
- Change VCS associations
Управление версиями Versioning
Разработка библиотек программного обеспечения редко завершается версией 1.0. A software library is rarely complete in version 1.0. Хорошая библиотека постоянно развивается: появляются новые функции, исправляются ошибки и повышается производительность. Good libraries evolve over time, adding features, fixing bugs, and improving performance. Очень важно правильно выпускать новые версии библиотеки .NET, расширяя ее возможности и не допуская появления проблем для уже существующих пользователей. It is important that you can release new versions of a .NET library, providing additional value with each version, without breaking existing users.
Критические изменения Breaking changes
См. сведения об оценке критических изменений между версиями. For information about handling breaking changes between versions, see Breaking changes.
Номера версий Version numbers
Для библиотеки .NET версию можно указать разными способами. A .NET library has many ways to specify a version. Вот несколько наиболее важных версий: These versions are the most important:
Версия пакета NuGet NuGet package version
Версия пакета NuGet отображается на сайте NuGet.org в диспетчере пакетов Visual Studio NuGet. Она добавляется к исходному коду при использовании пакета. The NuGet package version is displayed on NuGet.org, the Visual Studio NuGet package manager, and is added to source code when the package is used. Именно версию пакета NuGet чаще всего будут видеть пользователи и именно ее они будут считать версией используемой библиотеки. The NuGet package version is the version number users will commonly see, and they’ll refer to it when they talk about the version of a library they’re using. Версия пакета NuGet используется только в пределах NuGet и никак не влияет на поведение во время выполнения. The NuGet package version is used by NuGet and has no effect on runtime behavior.
Идентификатор пакета NuGet в сочетании с версией пакета NuGet используется для идентификации пакета в NuGet. The NuGet package identifier combined with the NuGet package version is used to identify a package in NuGet. Например, Newtonsoft.Json + 11.0.2 . For example, Newtonsoft.Json + 11.0.2 . Пакет с суффиксом обозначает пакет предварительной версии, и для него используются специальные правила, благодаря которым он идеально подходит для тестирования. A package with a suffix is a pre-release package and has special behavior that makes it ideal for testing. См. с сведения о пакетах предварительной версии. For more information, see Pre-release packages.
Так как версия пакета NuGet встречается разработчикам чаще всего, мы рекомендуем обновлять ее с использованием Семантического версионирования (SemVer). Because the NuGet package version is the most visible version to developers, it’s a good idea to update it using Semantic Versioning (SemVer). SemVer указывает на значимость изменений, реализованных в очередном выпуске, помогая разработчикам правильно выбрать версию для использования. SemVer indicates the significance of changes between release and helps developers make an informed decision when choosing what version to use. Например, переход от версии 1.0 к 2.0 указывает на наличие потенциальных критических изменений. For example, going from 1.0 to 2.0 indicates that there are potentially breaking changes.
✔ РЕКОМЕНДУЕТСЯ использовать SemVer 2.0.0 для управления версиями пакета NuGet. ✔️ CONSIDER using SemVer 2.0.0 to version your NuGet package.
✔️ СЛЕДУЕТ использовать версию пакета NuGet в общедоступной документации, так как именно этот номер версии пользователи будут видеть чаще всего. ✔️ DO use the NuGet package version in public documentation as it’s the version number that users will commonly see.
✔️ СЛЕДУЕТ добавить суффикс предварительной версии при выпуске нестабильной версии пакета. ✔️ DO include a pre-release suffix when releasing a non-stable package.
Чтобы использовать пакеты предварительных версий, пользователи должны явно согласиться с тем, что работа над пакетом еще не завершена. Users must opt in to getting pre-release packages, so they will understand that the package is not complete.
Версия сборки Assembly version
Версия сборки используется средой CLR во время выполнения для выбора загружаемой версии сборки. The assembly version is what the CLR uses at run time to select which version of an assembly to load. Выбор сборки через систему управления версиями применяется только к сборкам со строгими именами. Selecting an assembly using versioning only applies to assemblies with a strong name.
Среда CLR для .NET Framework при загрузке сборок со строгими именами требует точного соответствия. The .NET Framework CLR demands an exact match to load a strong-named assembly. Предположим, что Libary1, Version=1.0.0.0 компилируется со ссылкой на Newtonsoft.Json, Version=11.0.0.0 . For example, Libary1, Version=1.0.0.0 was compiled with a reference to Newtonsoft.Json, Version=11.0.0.0 . Тогда .NET Framework будет загружать только версию 11.0.0.0 . .NET Framework will only load that exact version 11.0.0.0 . Чтобы загрузить во время выполнения другую версию, необходимо добавить переадресацию привязок в файл конфигурации приложения .NET. To load a different version at run time, a binding redirect must be added to the .NET application’s config file.
Использование строгого именования в сочетании с версией сборки позволяет организовать строгую загрузку версий сборок. Strong naming combined with assembly version enables strict assembly version loading. Хотя строгое именование библиотек имеет ряд преимуществ, оно часто вызывает исключения времени выполнения, если не удается найти точную версию сборки. Для устранения таких проблем требуется исправление переадресации привязок в app.config или web.config . While strong naming a library has a number of benefits, it often results in run-time exceptions that an assembly can’t be found and requires binding redirects in app.config or web.config to be fixed. В .NET Core загрузка сборок менее строгая. In .NET Core, assembly loading is more relaxed. Среда выполнения .NET Core во время выполнения автоматически загружает сборки с более поздней версией. The .NET Core runtime automatically loads assemblies with a higher version at run time.
✔ РЕКОМЕНДУЕТСЯ указывать в AssemblyVersion только основной номер версии. ✔️ CONSIDER only including a major version in the AssemblyVersion.
Например, для библиотек версий 1.0 и 1.0.1 можно указать одинаковое значение AssemblyVersion 1.0.0.0 , а для библиотеки 2.0 изменить AssemblyVersion на 2.0.0.0 . e.g. Library 1.0 and Library 1.0.1 both have an AssemblyVersion of 1.0.0.0 , while Library 2.0 has AssemblyVersion of 2.0.0.0 . Если версия сборки меняется редко, потребуется меньше переадресаций привязок. When the assembly version changes less often, it reduces binding redirects.
✔ РЕКОМЕНДУЕТСЯ синхронизировать основной номер версии AssemblyVersion и версию пакета NuGet. ✔️ CONSIDER keeping the major version number of the AssemblyVersion and the NuGet package version in sync.
Номер AssemblyVersion включается в некоторые информационные сообщения для пользователей, например в составе имени сборки и имени типа сборки в сообщениях об исключениях. The AssemblyVersion is included in some informational messages displayed to the user, e.g. the assembly name and assembly qualified type names in exception messages. Сохранение связи между этими версиями позволит разработчикам лучше понимать, какую версию они используют. Maintaining a relationship between the versions provides more information to developers about which version they are using.
❌ НЕ СЛЕДУЕТ использовать фиксированное значение AssemblyVersion. ❌ DO NOT have a fixed AssemblyVersion.
Конечно же, отсутствие изменений в AssemblyVersion позволит избежать переадресации привязок, запрещая устанавливать более одной версии сборки в глобальный кэш сборок. While an unchanging AssemblyVersion avoids the need for binding redirects, it means that only a single version of the assembly can be installed in the Global Assembly Cache (GAC). Кроме того, приложения со ссылками на такую сборку в глобальном кэше сборок не смогут работать, если другое приложение загрузит в глобальный кэш сборок новую версию сборки с критическими изменениями. Also, the applications that reference the assembly in the GAC will break if another application updates the GAC assembly with breaking changes.
Версия файла сборки Assembly file version
Версия файла сборки используется для отображения версии файла в ОС Windows и никак не влияет на поведение во время выполнения. The assembly file version is used to display a file version in Windows and has no effect on run-time behavior. Настройка этой версии является необязательной. Setting this version is optional. Она отображается в диалоговом окне «Свойства файла» в проводнике Windows: It’s visible in the File Properties dialog in Windows Explorer:
✔ РЕКОМЕНДУЕТСЯ использовать номер сборки непрерывной интеграции в качестве номера редакции AssemblyFileVersion. ✔️ CONSIDER including a continuous integration build number as the AssemblyFileVersion revision.
Например, если вы создаете версию проекта 1.0.0, а номер сборки непрерывной интеграции имеет значение 99, параметр AssemblyFileVersion получит значение 1.0.0.99. For example, you are building version 1.0.0 of your project, and the continuous integration build number is 99 so your AssemblyFileVersion is 1.0.0.99.
✔️️ СЛЕДУЕТ использовать формат Major.Minor.Build.Revision для версии файла. ✔️ DO use the format Major.Minor.Build.Revision for file version.
Версия файла никогда не применяется в .NET, но в Windows ожидается версия файла в формате Major.Minor.Build.Revision . While the file version is never used by .NET, Windows expects the file version to be in the Major.Minor.Build.Revision format. Если версия не соответствует этому формату, появляется предупреждение. A warning is raised if the version doesn’t follow this format.
Информационная версия сборки Assembly informational version
Информационная версия сборки используется для сохранения дополнительных сведений о версии и никак не влияет на поведение во время выполнения. The assembly informational version is used to record additional version information and has no effect on runtime behavior. Настройка этой версии является необязательной. Setting this version is optional. Если вы используете SourceLink, это значение при сборке составляется из номера версии пакета NuGet и номера в системе управления версиями. If you’re using Source Link, this version will be set on build with the NuGet package version plus a source control version. Например, 1.0.0-beta1+204ff0a включает хэш фиксации для исходного кода, из которого построена сборка. For example, 1.0.0-beta1+204ff0a includes the commit hash of the source code the assembly was built from. Дополнительные сведения см. в разделе Ссылка на источник. For more information, see Source Link.
В более ранних версиях Visual Studio отображается предупреждение сборки, если эта версия не соответствует формату Major.Minor.Build.Revision . Older versions of Visual Studio raise a build warning if this version doesn’t follow the format Major.Minor.Build.Revision . Его можно игнорировать. The warning can be safely ignored.
❌ НЕЖЕЛАТЕЛЬНО самостоятельно указывать информационную версию сборки. ❌ AVOID setting the assembly informational version yourself.
Разрешите SourceLink автоматически создавать этот номер версии из метаданных NuGet и системы управления версиями. Allow SourceLink to automatically generate the version containing NuGet and source control metadata.
Version Control window
This tool window is available if version control integration is enabled for your project.
The tool window accommodates several views/tabs, which display VCS-related information and allow you to manage changelists, perform VCS-specific actions, view changes made by other team members, and so on:
Console tab: this tab shows the results of executing VCS-related commands.
Local Changes tab: shows a list of files that have been modified locally and have not been committed to the repository yet.
History tab: this tab is added to the Version Control window when the Show History command is invoked through VCS | .
Integrate to branch info view tab: this view is available after running integration with the Run status after update setting specified.
Log tab: this tab is only available if you are using Git or Mercurial as your version control system. It shows all changes committed to all branches of the local and remote repositories, or to a specific branch or repository.
Repository and Incoming tabs: the Repository tab shows the changes committed to the repository under the VCS roots within the current project. The Incoming tab shows the changes commited to the repository by other team members, and not checked out locally.
Shelf tab: this tab is added to the tool window when you shelve a change or a changelist.
Update Info tab: this tab becomes available when local information is synchronized with the server.
Title bar context menu and buttons
You can right-click the window title bar and use the context menu to configure its viewing mode, associate the window with a different tool window bar, or resize and hide the window.
You can also use the toolbar buttons:
Item | Shortcut | Description |
---|---|---|
Shift+Escape |