0

我已经知道你通常不能这样做,但这是我的情况:

我有一个非静态List<T>的,在正常使用期间添加,然后每隔一段时间转储到数据库中。我希望能够用来转储我尚未AppDomain.CurrentDomain.ProcessExit转储的任何值。每次转储时都会清除List<T>List

有没有什么方法可以在List没有给定上下文的情况下访问它,即使它是静态的-> 非静态的?

4

1 回答 1

1

只需将您的处理程序添加为 lambda,在它可以访问您的列表的范围内。

var list = new List<string>()
{
    "Item 1",
    "Item 2"
};

AppDomain.CurrentDomain.ProcessExit += (sender, theArgs) =>
{
    File.WriteAllLines(@"C:\temp\mylist.txt", list);
};

一种不错的方法是将这种行为封装在List<T>.

public class MyReallyPersistentList<T> : List<T>
{
    public MyReallyPersistentList()
    {
        AppDomain.CurrentDomain.ProcessExit += (sender, args) => 
        {
            var items = this.Select(i => i?.ToString());
            File.AppendAllLines(@"C:\temp\mylist.txt", items);
        };
    }
}
于 2016-04-18T20:42:33.493 回答