0

这是一个让我感到困惑的简单问题。

我有两个类和一个字典(为了示例而简化):

class Result {       
    public string Description;
}

class Error {
    public int ErrorCode;
}

Dictionary<int, string> errorCodeToMessage = new Dictionary<int, string> {
    { 0, "Item not found" },
    { 1, "Connection error" }
}

在我继承的代码库中,我经常看到这一行:

Result result = new Result {
    Description = errorCodeToMessage[error.ErrorCode];
}

我不希望字典被全部使用,我希望将此逻辑封装在Result对象或Error对象中。

我考虑在Result对象中创建一个新的构造函数,该构造函数将接受 ErrorCode 并在那里执行逻辑。但我不确定这是最好的方法。

你会怎么做?

4

2 回答 2

0

在 .NET 中,您应该为此使用ResourceManager 。这样,您就可以将所有可能的消息封装在它们所属的位置。

本质上,使用在整个应用程序中提供消息的实体没有任何问题——因为它是单例的一个很好的例子。但是,您可以将消息划分到不同的容器中。一个简单的例子:

enum ErrorCode
{
    SomethingIsWrong,
    AnotherThingIsWrong,
    UserIsAnIdiot
}

在一个ErrorCodes.resx文件中:

<data name="SomethingIsWrong" xml:space="preserve">
    <value>Something is wrong. Sorry!</value>
</data>
<data name="AnotherThingIsWrong" xml:space="preserve">
    <value>Another thing is wrong. Sorry!</value>
</data>
<data name="UserIsAnIdiot" xml:space="preserve">
    <value>You're an idiot! '{0:dd-MMM-yyyy}' is not a future date!</value>
</data>

你可以像这样使用它:

public void GetErrorMessage(ErrorCode errorCode)
{
    //ErrorCodes is a class accompanying the ErrorCodes.resx file
    var rm = new ResourceManager(typeof(ErrorCodes));

    //or with a CultureInfo instance if you want localized messages
    return rm.GetString(errorCode.ToString());
}

GetErrorMessage方法将在某种单例中,或在整个应用程序中使用的静态类中。您可以将消息类型彼此分开,将它们放入不同的 resx 文件中,这些文件将由 VS 生成的不同类包围。

于 2013-10-23T12:33:26.893 回答
0

我不明白为什么你有单独的 Result 和 Error 类。如果两者都描述一件事——某个事件的结果——那么它们应该被封装在一个代表它的对象中。然后,您可以在该类中保持字典私有。

简单的解决方案 - 以不同的方式思考。如果它看起来很难,请删除使它如此的位。

于 2013-10-23T12:31:13.857 回答