Visual C# 中用户定义的错误集合

发布于 2024-10-01 16:13:34 字数 2282 浏览 1 评论 0原文

我想编写一个用户定义的错误收集类,它应该收集所有错误。当我们验证实体对象时,如果没有错误,它应该保存到数据库中。如果有错误,它应该显示它。 现在我已经编写了该类,它收集错误并成功显示它,但是当存在两个相同的错误时,该类会引发异常。 (我使用错误代码来表示错误。错误代码的值位于 resx 文件中,显示方法将从该文件中获取该值并显示它。显示工作正常)

//The code where it collects Error 
if (objdepartment.Departmentname == null)
{
    ErrorCollection.AddErrors("A1001","Department Name");
}
if (objdepartment.Departmentcode == null)
{
    ErrorCollection.AddErrors("A1001","Department code");
}

//In the Errorcollection  

public class ErrorCollection
{
    static Dictionary<string,List<string>> ErrorCodes;
    private ErrorCollection() { }

    public static void AddErrors(string eCode,params string[] dataItem)
    {
        if (ErrorCodes == null)
        {
            ErrorCodes = new Dictionary<string, List<string>>();
        }
        List<String> lsDataItem = new List<String>();
        foreach (string strD in dataItem)            
            lsDataItem.Add(strD);
        ErrorCodes.Add(eCode, lsDataItem);
    }

    public static string DisplayErrors()
    {
        string ErrorMessage;
        //string Key;
        ErrorMessage = String.Empty;
        if (ErrorCodes != null)
        {
            string Filepath= "D:\\Services\\ErrorCollection\\";
            //Read Errors- Language Specsific message from resx file.
            ResourceManager rm = ResourceManager.CreateFileBasedResourceManager("ErrorMessages", Filepath, null);
            StringBuilder sb = new StringBuilder();
            foreach (string error in ErrorCodes.Keys)
            {                
                List<string> list = ErrorCodes[error];
                if (error == "A0000")
                {
                    sb.Append("System Exception : " + list[0]);
                }
                else
                {
                    sb.Append(rm.GetString(error) + "\nBreak\n");
                }

                for (int counter = 0; counter < list.Count; counter++)
                {
                    sb.Replace("{A}", list[counter]);
                }
            }
            ErrorMessage = sb.ToString();
        }
        return ErrorMessage;
    }
}    

现在有两个常见错误。然后代码在“ErrorCodes.Add(eCode, lsDataItem);”行中显示类似“datakey已经存在”的异常(抛出异常的斜体部分)

I want to write an user defined error collection class which should collect all the Error's. When we validate an entity object if there is no error it should go and save to the Database. if Error there it should display it.
now i have wrote the class it collects the error and displays it successfully but when there is two identical error the class throws an exception.
(i use error-code for the error. the value for the error-code is in resx file from where the display method will take the value and display it. Display works perfectly)

//The code where it collects Error 
if (objdepartment.Departmentname == null)
{
    ErrorCollection.AddErrors("A1001","Department Name");
}
if (objdepartment.Departmentcode == null)
{
    ErrorCollection.AddErrors("A1001","Department code");
}

//In the Errorcollection  

public class ErrorCollection
{
    static Dictionary<string,List<string>> ErrorCodes;
    private ErrorCollection() { }

    public static void AddErrors(string eCode,params string[] dataItem)
    {
        if (ErrorCodes == null)
        {
            ErrorCodes = new Dictionary<string, List<string>>();
        }
        List<String> lsDataItem = new List<String>();
        foreach (string strD in dataItem)            
            lsDataItem.Add(strD);
        ErrorCodes.Add(eCode, lsDataItem);
    }

    public static string DisplayErrors()
    {
        string ErrorMessage;
        //string Key;
        ErrorMessage = String.Empty;
        if (ErrorCodes != null)
        {
            string Filepath= "D:\\Services\\ErrorCollection\\";
            //Read Errors- Language Specsific message from resx file.
            ResourceManager rm = ResourceManager.CreateFileBasedResourceManager("ErrorMessages", Filepath, null);
            StringBuilder sb = new StringBuilder();
            foreach (string error in ErrorCodes.Keys)
            {                
                List<string> list = ErrorCodes[error];
                if (error == "A0000")
                {
                    sb.Append("System Exception : " + list[0]);
                }
                else
                {
                    sb.Append(rm.GetString(error) + "\nBreak\n");
                }

                for (int counter = 0; counter < list.Count; counter++)
                {
                    sb.Replace("{A}", list[counter]);
                }
            }
            ErrorMessage = sb.ToString();
        }
        return ErrorMessage;
    }
}    

now when there is two common error. then the code shows an exception like "datakey already exist" in the line " ErrorCodes.Add(eCode, lsDataItem);" (the italic part where the exception throwed)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

相思故 2024-10-08 16:13:34

一方面,静态这是一个糟糕的主意。您应该创建 ErrorCollection实例以将错误添加到 IMO,并使该变量成为实例变量而不是静态变量。

然后,您需要在 AddErrors 中采取不同的方法,如果密钥已经存在,则可能添加所有新项目。像这样的东西:

List<string> currentItems;
if (!ErrorCodes.TryGetValue(eCode, out currentItems))
{
    currentItems = new List<string>);
    ErrorCodes[eCode] = currentItems;
}
currentItems.AddRange(dataItem);

Well for one thing, having this statically is a terrible idea. You should create an instance of ErrorCollection to add the errors to IMO, and make the variable an instance variable instead of static.

Then you need to take a different approach within AddErrors, presumably adding all the new items if the key already exists. Something like this:

List<string> currentItems;
if (!ErrorCodes.TryGetValue(eCode, out currentItems))
{
    currentItems = new List<string>);
    ErrorCodes[eCode] = currentItems;
}
currentItems.AddRange(dataItem);
丑丑阿 2024-10-08 16:13:34

您将“A1001”添加两次作为字典中的键。这根本就是不允许的。然而,更紧迫的是 - 为什么该字典是静态的?这意味着任何地方的所有事物都共享该错误集合。

建议:

  • 使其不是静态的(这是一个坏主意 - 而且它不同步)
  • 检查密钥是否存在,并做出相应的反应:

    if(ErrorCodes.ContainsKey(eCode)) ErrorCodes[eCode].AddRange(lsDataItem);
    否则 ErrorCodes.Add(eCode, lsDataItem);
    

顺便说一句,您还可以考虑实施 IDataErrorInfo,这是此类功能的内置标准包装器,将为您的错误收集提供支持带有一些标准 API。但在需要之前不要急于这样做;p

You are adding "A1001" twice as a key in a dictionary. That simply isn't allowed. However, more urgently - why is that dictionary static? That means that everything, anywhere, shares that error collection.

Suggestions:

  • make that not static (that is a bad idea - also, it isn't synchronized)
  • check for existence of the key, and react accordingly:

    if(ErrorCodes.ContainsKey(eCode)) ErrorCodes[eCode].AddRange(lsDataItem);
    else ErrorCodes.Add(eCode, lsDataItem);
    

As an aside, you might also consider implementing IDataErrorInfo, which is a built-in standard wrapper for this type of functionality, and will provide support for your error collection to work with a few standard APIs. But don't rush into this until you need it ;p

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文