Compiling Resources into Assemblies



When you build your application, Visual Studio invokes the resgen.exe tool to convert your application resources into an internal class called Resources. This class is contained in the Resources.Designer.cs file which is nested under the Resources.resx file in Solution Explorer. The Resources class encapsulates all your project resources into static readonly get properties as a way of providing strongly-typed resources at run-time. When you build through the Visual C# IDE, all the encapsulated resource data, including both the resources that were embedded into the .resx file and the linked files, is compiled directly into the application assembly (the .exe or .dll file). In other words, the Visual C# IDE always uses the /resource compiler option. If you build from the command line, you can specify the /linkresource compiler option that will enable you to deploy resources in a separate file from the main application assembly. This is an advanced scenario and is only necessary in certain rare situations. A more common scenario for deploying resources separately from the main application assembly is to use satellite assemblies as discussed below.

Accessing Resources at Run-Time

To access a resource at run-time, simply reference it as you would any other class member. The following example shows how to retrieve a bitmap resource that you named Image01. Note that the Resources class is in a namespace called <projectName>.Properties, so you must either user the fully qualified name for each resource or else add the appropriate using directive in the source file from which you are accessing the Resources class.

System.Drawing.Bitmap bitmap1 = myProject.Properties.Resources.Image01;

Internally the get property uses the ResourceManager class to create a new instance of the object.

 


Компиляция ресурсов в сборки

При построении приложения Visual Studio вызывает средство resgen.exe для преобразования ресурсов приложения во внутренний класс с именем Resources. Этот класс находится в файле Resources.Designer.cs, который вложен в файл Resources.resx в Обозревателе решений. Класс Resources инкапсулирует все ресурсы проекта в статические свойства get только для чтения, что дает возможность получения строго-типизированных ресурсов во время выполнения. Во время построения в интегрированной среде разработки Visual C# все инкапсулированные данные ресурсов, включая как внедренные в файл RESX, так и связанные файлы, компилируются непосредственно в сборку приложения (файл EXE или DLL). Другими словами, интегрированная среда разработки Visual C# всегда использует параметр компилятора /resource. При построении из командной строки можно указать параметр компилятора /linkresource, что позволит развернуть ресурсы в отдельном файле из основной сборки приложения. Это дополнительная возможность, которая может потребоваться в исключительно редких случаях. Более типичный сценарий развертывания ресурсов из основной сборки приложения заключается в использовании вспомогательных сборок (см. описание далее).

Доступ к ресурсам во время выполнения

Чтобы получить доступ к ресурсу во время выполнения, просто создайте ссылку на него, как на любой другой член класса. В следующем примере демонстрируется получение ресурса растрового изображения с именем “Image01”. Следует отметить, что класс ресурсов входит в пространство имен с именем <projectName>.Properties, поэтому необходимо указать либо полное для имя каждого ресурса, либо добавить соответствующую директиву using в исходный файл, из которого осуществляется доступ к классу ресурсов.

System.Drawing.Bitmap bitmap1 = myProject.Properties.Resources.Image01;

Класс ResourceManager используется внутри свойством получения для создания нового экземпляра объекта.

 


Getting Help

The Help documentation for Visual Studio is in the MSDN Library, which you can install locally on your own computer or network, and which is also available on the Internet. The local version of the library consists of a collection of compressed HTML files in the .hxs format. You can decide to install either all or part of the library on your computer; the complete MSDN installation is close to 2GB and it includes documentation for many Microsoft technologies. You can view both the local and the online MSDN documentation by using the Visual Studio Help browser called Microsoft Document Explorer.

There are eight ways to access documentation when you are working in Visual C#:

· F1 Search

· Search

· Index

· Table of Contents

· Help Favorites

· How Do I

· Dynamic Help

· Samples

Online vs. Local Help

On the Help Options property page under the Options menu, you can specify the following options for search and F1 search behavior:

· Try the online MSDN library first, and then the local documentation if no match is found.

· Try the local MSDN library first, and then the online documentation if no match is found.

· Try only the local MSDN library.

These options will also appear the first time that you invoke any search. The online MSDN documentation may contain more recent updates than the local documentation. Therefore, if you have an Internet connection and are working in Visual C#, set the search option to try the online MSDN library first. From time-to-time, updates to local documentation may be made available for download.


Получение справки

Справочная документация для Visual Studio находится в библиотеке MSDN, которую можно установить локально на компьютер или разместить в сетевой папке. Библиотека также доступна в Интернете. Локальная версия библиотеки включает набор сжатых HTML-файлов в формате HSX. Библиотеку можно установить на компьютере полностью или частично; для полной установки библиотеки MSDN потребуется до 2 ГБ, поскольку в ней содержится документация для многих технологий Microsoft. Как локальную документацию MSDN, так и документацию в Интернете можно просматривать при помощи обозревателя справки Visual Studio – Microsoft Document Explorer.

Всего существует восемь способов доступа к документации при работе в Visual C#:

· Поиск по F1

· Поиск

· Указатель

· Содержание

· Избранные разделы справки

· Инструкции

· Динамическая справка

· Примеры


Дата добавления: 2019-03-09; просмотров: 238; Мы поможем в написании вашей работы!

Поделиться с друзьями:






Мы поможем в написании ваших работ!