15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

582 ❘ ChaPTer 22 lOcAlizAtiOn<br />

namespace Wrox.ProCSharp.Localization<br />

{<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

var rm = new ResourceManager("Wrox.ProCSharp.Localization.Demo",<br />

Assembly.GetExecutingAssembly());<br />

code snippet ResourceDemo/Program.cs<br />

Using the ResourceManager instance rm, you can get all the resources by specifying the key to the methods<br />

GetObject() <strong>and</strong> GetString():<br />

}<br />

}<br />

}<br />

Console.WriteLine(rm.GetString("Title"));<br />

Console.WriteLine(rm.GetString("Chapter"));<br />

Console.WriteLine(rm.GetString("Author"));<br />

using (Image logo = (Image)rm.GetObject("WroxLogo"))<br />

{<br />

logo.Save("logo.bmp");<br />

}<br />

With strongly typed resources, the code written earlier can be simplified; there is no need to instantiate the<br />

ResourceManager <strong>and</strong> access the resources using indexers. Instead, the names of the resources are accessed<br />

with properties:<br />

private static void StronglyTypedResources()<br />

{<br />

Console.WriteLine(Demo.Title);<br />

Console.WriteLine(Demo.Chapter);<br />

Console.WriteLine(Demo.Author);<br />

using (Bitmap logo = Demo.WroxLogo)<br />

{<br />

logo.Save("logo.bmp");<br />

}<br />

}<br />

To create a strongly typed resource with the Managed Resources Editor, the Access Modifier can be<br />

reset from No Code Generation to Public or Internal. With Public, the generated class has a public access<br />

modifier <strong>and</strong> is available from other assemblies. With Internal, the generated class has an internal<br />

access modifier <strong>and</strong> can only be accessed from within the assembly.<br />

When you set this option, the class Demo (it has the same name as the resource) is created. This class has<br />

static properties for all the resources to provide a strongly typed resource name. With the implementation of<br />

the static properties, a ResourceManager object is used that is instantiated on first access <strong>and</strong> then cached:<br />

//------------------------------------------------------------------------------<br />

// <br />

// This code was generated by a tool.<br />

// Runtime Version:4.0.21006.1<br />

//<br />

// Changes to this file may cause incorrect behavior <strong>and</strong> will be lost if<br />

// the code is regenerated.<br />

// <br />

//------------------------------------------------------------------------------<br />

namespace Wrox.ProCSharp.Localization {<br />

using System;<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!