List.Add()重新添加以前的值

时间:2017-11-11 18:08:39

标签: c# list logging

背景: 我正在开发一个控制台应用程序,每行保存到指定的日期日志文件(例如2017年1月5日是01_05_2017_log_.txt)

每个日志都按其应有的方式添加,但我似乎无法弄清楚的问题是为什么它会再次添加包含日志值的List的所有先前值。

因此,当调用CurrentLogs.Add("Some log here")时,它会将Some log here添加到CurrentLogs列表中。

让我们再次调用它,但这次使用的字符串是another log here。列表中的项目如下:

  • 有人在这里登录
  • 有人在这里登录
  • 另一个日志

如果我再次尝试使用.Add方法,则会重新添加3个

我看了看周围的方式,bing,google,无济于事。

// This is the List object I'm using.
public class LoggerList<T> : List<T>
{
    public event EventHandler OnAdd;
    public new void Add(T item)
    {
        OnAdd?.Invoke(this, null);
        base.Add(item);
    }
}

现在这里是Logger类,其中Logger.CurrentLogs.Add()被称为f rom

public class Logger
{
    // Directory in which logs are stored
    private static string _loggerPath = "Logs/";
    // Used to check if the Old Logs have already been added to the OldLogs Object
    private static bool _alreadyPulled = false;
    // Previously saved logs before the current use of the console app
    private static readonly List<string> OldLogs = new List<string>();
    // Current logs to be added here
    public static LoggerList<string> CurrentLogs = new LoggerList<string>();

    //EventHandler to Save Logs on add
    public static void OnAdd(object sender, EventArgs e)
    {
        SaveLog();
    }

    /// <summary>
    /// Saves the logs
    /// </summary>
    public static void SaveLog()
    {
        if (!Directory.Exists(_loggerPath))
        {
            Directory.CreateDirectory(_loggerPath);
        }

        string fileName = _loggerPath + DateTime.Now.ToString("MM_dd_yyyy") + "_log_.txt";
        // If the File Exists, contiue with loading
        if (File.Exists(fileName))
        {
            // If the OldLogs have not already been pulled, pull them
            if (!_alreadyPulled)
            {
                var oldLogs = File.ReadAllLines(fileName).ToList();
                foreach (var i in oldLogs)
                {
                    OldLogs.Add(i);
                }
                _alreadyPulled = true; // Let know that the OldLogs have already been pulled this instance
            }
            List<string> lines = OldLogs;
            lines.AddRange(CurrentLogs);
            File.Delete(fileName);

            var sr = File.CreateText(fileName);
            foreach (string x in lines)
            {
                sr.WriteLine(x);
            }
            sr.Flush();
            sr.Close();
        }
        // Only go here if the file doesn't exist
        else
        {
            var sr = File.CreateText(fileName);
            foreach (string x in CurrentLogs)
            {
                sr.WriteLine(x);
            }
            sr.Flush();
            sr.Close();
        }
    }
}

这是Program.cs(添加此项,因为这是调用Messenger类的地方     课程     {         static void Main(string [] args)         {             Logger.CurrentLogs.OnAdd + = Logger.OnAdd;             CommandManager.InitCommands();             CheckForEntries();

    }

    private static void CheckForEntries()
    {
        while (true)
        {
            Console.ForegroundColor = ConsoleColor.White;
            var text = Console.ReadLine();
            try
            {
                if (!SendEntry(text))
                {
                    Console.WriteLine("Failed to send");
                }
            }
            catch (CommandNotFoundException ex)
            {
                Messenger.Send("Commmand does not exist (" + text.GetWords()[0] + ")");
            }
        }
    }

    private static bool SendEntry(string text)
    {
        try
        {
            if (text.FirstCharacter() != "/")
            {
                return false;
            }
            else
            {
                string text2 = text.Substring(1);
                string commandname = text2.GetWords()[0];
                foreach (Command c in CommandManager.RegisteredCommands)
                {
                    if (c.Name.ToLower() == commandname.ToLower())
                    {
                        c.Run(text2.Substring(commandname.Length));
                        return true;
                    }
                    else
                    {
                        foreach (string alias in c.Aliases)
                        {
                            if (alias.ToLower() == commandname.ToLower())
                            {
                                c.Run(text2.Substring(commandname.Length + 1));
                                return true;
                            }
                        }
                    }
                }
                throw new CommandNotFoundException();
            }
        }
        catch (CommandNotFoundException ex)
        {
            throw ex; // Placed here so that the catch (Exception) does not go beyond
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            return false;
        }
    }


}

这里是Messenger.cs(.Add直接发生的地方)

// Color codes
private static readonly string[] codes =
    {
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
        "a", "b", "c", "d", "e", "f"
    };

    private static string Format(string rawText)
    {
        return "&e" + TimeStamp() + " " + rawText;
    }

    public static string TimeStamp()
    {
        return "<" + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss") + ">";
    }
    public static void Send(string textRaw)
    {
        Logger.CurrentLogs.Add(Format(textRaw).Substring(2));
        string text = Format(textRaw);
        List<int> skipOver = new List<int>();
        for (int txt = 0; txt <= text.Length - 1; txt++)
        {
            char[] chars = text.ToCharArray();
            if (chars[txt].ToString() == "&")
            {
                List<string> hi = codes.ToList();
                if (hi.Contains(chars[txt + 1].ToString().ToLower()))
                {
                    skipOver.Add(txt);
                    skipOver.Add(txt + 1);
                }
            }
        }

        for (int x = 0; x <= text.Length - 1; x++)
        {

            char[] chars = text.ToCharArray();
            if (chars[x] == "&".ToCharArray()[0]) continue;
            if (x <= 1 || skipOver.Contains(x)) continue;
            char behind2 = chars[x - 2];
            char behind1 = chars[x - 1];
            if (behind2.ToString() == "&")
            {
                bool isGoodCode = false;
                foreach (string s in codes)
                {
                    if (s.ToLower() == behind1.ToString().ToLower())
                    {
                        isGoodCode = true;
                    }
                }

                if (isGoodCode)
                {
                    skipOver.Add(x - 2);
                    skipOver.Add(x - 1);
                    if (x < text.Length - 1)
                    {
                        Color baseColor = ToColor(behind1.ToString());
                        ConsoleColor cColor = ToConsoleColor(baseColor);
                        Console.ForegroundColor = cColor;
                        Console.Write(chars[x]);
                    }
                    else if (x == text.Length - 1)
                    {
                        Color baseColor = ToColor(behind1.ToString());
                        ConsoleColor cColor = ToConsoleColor(baseColor);
                        Console.ForegroundColor = cColor;
                        Console.WriteLine(chars[x]);
                    }
                }
                else
                {
                    if (x < text.Length - 1)
                    {
                        Console.Write(chars[x - 2]);
                        Console.Write(chars[x - 1]);
                        Console.Write(chars[x]);
                    }
                    else if (x == text.Length - 1)
                    {
                        Console.Write(chars[x - 2]);
                        Console.Write(chars[x - 1]);
                        Console.WriteLine(chars[x]);
                    }
                }
            }
            else
            {
                if (x < text.Length - 1)
                {
                    Console.Write(chars[x]);
                }
                else if (x == text.Length - 1)
                {
                    Console.WriteLine(chars[x]);
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

在这些行中

List<string> lines = OldLogs;
lines.AddRange(CurrentLogs);

&#34;线&#34;指向与#34; OldLogs&#34;相同的对象。因此,您不断在同一列表中添加条目。

您可以尝试复制:

var lines = new List<string>(OldLogs);