日期:2014-05-17  浏览次数:21070 次

xml序列化
大家帮我看一下,这个类序列化后,xml里面怎么没有username和userpwd呢?
C# code
  [Serializable]
    public class Program
    {
        private const string Path = "temp.xml";
        private static Program p = new Program();
        private string _userName;

        public static string UserName
        {
            get { return p._userName; }
            set { p._userName = value; }
        }

        private string _userPwd;

        public static string UserPwd
        {
            get { return p._userPwd; }
            set { p._userPwd = value; }
        }
        public Program()
        {

        }
        public void Serializable()
        {
            using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + Path, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                XmlSerializer xs = new XmlSerializer(typeof(Program));
                xs.Serialize(fs, p);
            }
        }
        public static void Save()
        {
            p.Serializable();
        }
        static void Main(string[] args)
        {
            Program.UserName = "aaa";
            Program.UserPwd = "bbb";
            Program.Save();
        }
    }


------解决方案--------------------
public static string UserName
=>
public string UserName

静态属性是不参与序列化的
------解决方案--------------------
不能用Static的。
最好定义一个数据类

public class User
{
public string UserName{get;set;}
public string UserPwd{get;set;}
}
 public void Serializable(User u)
{
 using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + Path, FileMode.Create, FileAccess.Write, FileShare.None))
{
XmlSerializer xs = new XmlSerializer(typeof(User));
xs.Serialize(fs, u);
}
}