















2010-09-08 07:33 w i n s o n 阅读(1125) 评论() 收藏 举报
这段时间以来,我都被这个问题困扰着,如何能在类库中直接调用资源文件以达到国际化效果呢?
因为资源文件只存在于UI层面,所以底层类库不能直接调用,曾考虑过在底层直接返回信息代码,然后在UI层显示,但当遇到需要直接在底层写日志的时候,这种方式就不行了。
然后又想到了干脆将所有资源文件都做成一个独立的类库,这样不管在哪里都可以直接调用了,但另一个问题又来了,就是如果这样做后,那就会造成每修改一次资源文件,就要重新编译整个项目,即当程序发布后,用户就不能方便地对资源文件进行修改了,所以这样做也不方便。
那有没有更好的方法呢?呵,最近在研究 ScrewTurn Wiki 系统,发现有非常多值得学习的地方,其中就有在类库中调用资源文件的方法,其实原理也很简单,就是使用接口,达到后期绑定的效果,UI实现了获取资源的接口后,在类库里再调用此接口,就可以达到所要的效果了。
当然,并没有两全其美的办法,使用此方法的一个弊端就是,在调用接口获取资源文件时,不能使用智能提示的方式直接点出相关的KEY,只能手工输入一个字符串的KEY,再根据KEY以获取具体的语言信息,其实就是使用了 ResourceManager 的 GetString 方法实现的,以下是具体的代码:
1、先创建 IResource 接口:
代码
/// <summary>
/// 发布接口以获取资源
/// </summary>
public interface IResource
{
/// <summary>
/// 获取对应资源.
/// </summary>
/// <param name="name">资源名称,即KEY.</param>
/// <returns>对应的资源.</returns>
string GetResource(string name);
}
2、在UI层实现此接口:
代码
/// <summary>
/// 实现资源文件获取接口
/// </summary>
public class CoreResource : IResource
{
/// <summary>
/// 资源文件类型,即类名
/// </summary>
private string cagetory;private ResourceManager manager;/// <summary>
/// 初始化,创建 ResourceManager 对象
/// </summary>
public CoreResource(string resourceCagetory)
{
if (string.IsNullOrEmpty(resourceCagetory))
cagetory = "CoreMessages";
else
cagetory = resourceCagetory;
//缓存调用
string cacheKey = "Resources_" + cagetory;
object resources = CacheHelper.Get(cacheKey);
resources = null;
if (resources == null)
{
//利用反射来动态获取对应的资源文件类
manager = (ResourceManager)System.Type.GetType
("Resources." + cagetory).GetProperty("ResourceManager",
BindingFlags.Static | BindingFlags.NonPublic).GetValue(null, null);
CacheHelper.Insert(cacheKey, manager);
}
3、在类库层里调用 IResource 接口:
代码
/// <summary>
/// 在类库层面获取资源
/// </summary>
public static class Resource
{
private static IResource coreMessage;/// <summary>
/// 获取或设置资源对象
/// </summary>
public static IResource CoreMessage
{
get { return coreMessage; }
set { coreMessage = value; }
}
}
4、最后在需要的地方直接调用即可,如在类库写日志时调用:
Log.LogEntry(Resource.CoreMessage.GetResource("Provider_AlreadyInMemory"), EntryType.Warning, Log.SystemUsername);
上面也说过,此方法的缺点就是在调用时要手工输入相应的KEY的字符串,这也有可能会导致万一输入错了KEY,就会报错了,所以在获取时最好加上异常处理,以防止运行时的错误,至于这个问题,我个人觉得比起不能调用要好些啦,呵呵
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。