你所描述的行为适合Queue。但.Net队列的问题是它不能直接保存到独立存储(序列化问题)。既然你只有20个元素足以使用列表,并且只需删除第一个元素。
private List<string> messages = new List<string>(MAX_ITEMS);
private const int MAX_ITEMS = 20;
private void userAddMessege(string message)
{
messages.Add(message);
if (messages.Count > MAX_ITEMS)
{
messages.RemoveAt(0);
}
}
我假设你想使用IsolatedStorage,因为你想,当用户退出你的应用程序保存消息和恢复用户回来的消息。我用一个简单的包装
using System;
using System.Net;
using System.Windows;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace YourProjectNamespace
{
public class AppSettings
{
// Isolated storage settings
private IsolatedStorageSettings m_isolatedStore;
public AppSettings()
{
try
{
// Get the settings for this application.
m_isolatedStore = IsolatedStorageSettings.ApplicationSettings;
}
catch (Exception e)
{
MessageBox.Show("Exception while using IsolatedStorageSettings: " + e.ToString());
}
}
/// <summary>
/// Update a setting value for our application. If the setting does not
/// exist, then add the setting.
/// </summary>
/// <param name="Key">Key to object</param>
/// <param name="value">Object to add</param>
/// <returns>if value has been changed returns true</returns>
public bool AddOrUpdateValue(string Key, Object value)
{
bool valueChanged = false;
try
{
if (m_isolatedStore.Contains(Key))
{
// if new value is different, set the new value.
if (m_isolatedStore[Key] != value)
{
m_isolatedStore[Key] = value;
valueChanged = true;
}
}
else
{
m_isolatedStore.Add(Key, value);
valueChanged = true;
}
}
catch (ArgumentException)
{
m_isolatedStore.Add(Key, value);
valueChanged = true;
}
catch (Exception e)
{
MessageBox.Show("Exception while using IsolatedStorageSettings: " + e.ToString());
}
return valueChanged;
}
/// <summary>
/// Get the current value of the setting, or if it is not found, set the
/// setting to an empty List.
/// </summary>
/// <typeparam name="valueType"></typeparam>
/// <param name="Key"></param>
/// <returns></returns>
public List<DefType> GetListOrDefault<DefType>(string Key)
{
try
{
if (m_isolatedStore.Contains(Key))
{
return (List<DefType>)m_isolatedStore[Key];
}
else
{
return new List<DefType>();
}
}
catch (ArgumentException)
{
return new List<DefType>();
}
catch (Exception e)
{
MessageBox.Show("Exception while using IsolatedStorageSettings: " + e.ToString());
}
return new List<DefType>();
}
public List<String> Messages
{
get
{
return this.GetListOrDefault<String>("Messeges");
}
set
{
this.AddOrUpdateValue("Messeges", value);
this.Save();
}
}
/// <summary>
/// Delete all data
/// </summary>
public void DeleteAll()
{
m_isolatedStore.Clear();
}
/// <summary>
/// Save the settings.
/// </summary>
public void Save()
{
m_isolatedStore.Save();
}
}
}
然后,只需添加到页面
private AppSettings m_appSettings = new AppSettings();
从IsolatedStorage得到消息:
var messages = m_appSettings.Messages;
拯救他们:
m_appSettings.Messages = messages;
这只保存一个项目。 请帮忙 – 2012-06-18 16:25:10