使用 ResourceManager 类检索资源(来自MSDN)

可以使用 ResourceManager 类在运行时检索“嵌入的资源”(即已经编译到应用程序或类库中的资源)。ResourceManager 类的每个实例都与一个程序集关联并且管理对嵌入到该程序集中的资源的检索。

检索资源

  1. 创建一个程序集引用,引用包含要访问的资源的程序集。如果尚未加载包含资源的程序集,则必须在此时加载它。
  2. 创建 ResourceManager 类的实例以检索资源。
  3. 指定嵌入文件的基名称并提供对包含资源的程序集的引用。
    注意   嵌入的资源文件的基名称是嵌入了资源文件的命名空间的名称加上不带任何扩展名的文件名。例如,myApplication 命名空间中名为 Resource1.resX 的文件的基名称是 myApplication.Resource1。
  4. 调用 ResourceManager.GetString 方法ResourceManager.GetObject 方法以检索资源。
    • 若要检索“字符串”资源,请调用 GetString 方法。
    • 若要检索其他类型的资源,请调用 GetObject 方法。通过 GetObject 方法检索到的资源必须显式转换成对应的类型。

 

//  C#
//  Gets a reference to the same assembly that 
//  contains the type that is creating the ResourceManager.
System.Reflection.Assembly myAssembly;
MyAssembly 
=   this .GetType().Assembly;

//  Gets a reference to a different assembly.
System.Reflection.Assembly myOtherAssembly;
myOtherAssembly 
=  System.Reflection.Assembly.Load( " ResourceAssembly " );

//  Creates the ResourceManager.
System.Resources.ResourceManager myManager  =   new  
   System.Resources.ResourceManager(
" ResourceNamespace.myResources "
   myAssembly);

//  Retrieves String and Image resources.
System.String myString;
System.Drawing.Image myImage;
myString 
=  myManager.GetString( " StringResource " );
myImage 
=  (System.Drawing.Image)myManager.GetObject( " ImageResource " );
C#中,`ResourceManager`是一个强大的工具,用于管理和提供应用程序的本地化字符串资源。以下是如何使用它的步骤: 1. **创建资源文件**: 首先,为你的资源创建一个.resx文件。例如,假设你有一个资源文件名为`Strings.resx`,在这个文件中,你会添加各种键值对,键通常是字符串常量,值是你想本地化的文本。 2. **引用资源文件**: 在你的库中,通过命名空间引用资源文件。在`using`声明中添加`System.Resources.ResourceManager`。 ```csharp using System.Resources; ``` 3. **初始化ResourceManager**: 创建一个`ResourceManager`实例,指定资源文件的名称和所在的 assembly(通常就是你的应用程序的 assembly)。 ```csharp private static ResourceManager resourceManager; static MyClassName() { resourceManager = new ResourceManager("MyNamespace.Strings", typeof(MyClassName).Assembly); } ``` 4. **加载和获取资源**: 通过`GetString`方法,传入你想使用的键名,就可以获取到对应的本地化字符串。 ```csharp string greeting = resourceManager.GetString("Greeting"); ``` 5. **错误处理**: 如果资源文件中找不到指定的键,`GetString`会返回空字符串或默认值。如果需要自定义错误处理,可以捕获`MissingManifestResourceException`异常。 ```csharp try { string message = resourceManager.GetString("NonExistentKey"); } catch (MissingManifestResourceException ex) { Console.WriteLine($"Resource not found: {ex.Message}"); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值