C#使用特性自动保存属性值
本文导读:很多时候需要在程序退出时保存一些属性值,用于再次启动时恢复状态;本文利用自定义特性对属性进行标记,实现自动保存标记属性的值;目前来说只能保存基础数据类型的值。
自定义特性:
自定义特性继承自 System.Attribute类;可以定义特性的一些属性,用于设置特性时初始化。例如系统自带的控件的大多数属性都会使用特性作为标记 [SRCategoryAttribute("CatLayout")]表示Width属性在设计编辑器中属于“CatLayout”类。
//
// 摘要:
// 获取或设置控件的宽度。
//
// 返回结果:
// 控件的宽度(以像素为单位)。
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[EditorBrowsable(EditorBrowsableState.Always)]
[SRCategoryAttribute("CatLayout")]
[SRDescriptionAttribute("ControlWidthDescr")]
public int Width { get; set; }
自定义特性代码:
class SaveAttribute : Attribute
{
public SaveAttribute(string saveName)
{
SaveName = saveName;
}
/// <summary>
/// 保存名称
/// </summary>
public string SaveName;
}
标记属性:
在需要保存属性的界面中的属性添加SaveAttribute特性;
/// <summary>
/// 当前车牌号;推出界面是需要保存
/// </summary>
[SaveAttribute("CurrentCart")]
public string CurrentCart { get; set; }
属性值保存:
using System.Reflection;
///属性值保存
private void SaveValue()
{
using (StreamWriter sw = File.CreateText("1.txt"))
{
//保存界面信息
PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var v in properties)
{
//v.CustomAttributes.Contains()
SaveAttribute at = v.GetCustomAttribute(typeof(SaveAttribute)) as SaveAttribute;
if (at != null)
{
object value = v.GetValue(this, null);
sw.WriteLine("{0}={1}", v.Name, value);
Console.WriteLine(v.Name);
}
}
}
}
属性值恢复:
private void ReadValue()
{
if (!File.Exists("1.txt")) return;
using (StreamReader sw = File.OpenText("1.txt"))
{
string str = null;
while ((str = sw.ReadLine()) != null)
{
string[] strs = str.Split('=');
System.Reflection.PropertyInfo propertyInfoName = (this.GetType()).GetProperty(strs[0]);
propertyInfoName.SetValue(this, string.IsNullOrEmpty(strs[1]) ? "": strs[1]);
}
}
}