私有字段未发生二进制序列化 [英] Binary Serialization not happening for Private field
本文介绍了私有字段未发生二进制序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我假设在二进制序列化中,我们可以序列化任何成员,无论它们是私有的,公共的,内部的还是受保护的,我知道的唯一条件是它应该具有默认的构造函数,以便进行序列化和反序列化.但是,在下面的示例中,我们无法对私人领域的工资进行服务
Hi I am assuming in Binary Serialization we can serialize any members irrespective of whether they are private or public or internal or protected, the only condition I am aware is that it should have a default constructor in order serialize and de-serialize. However in my below example we are not able to seriliaze private field salary
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace BinarySerilization
{
[Serializable]
class Employee
{
public int Empid { get; set; }
public String Empname { get; set; }
public String Emplocation { get; set; }
private int Empsalary;
public int EmpSalary { get; set; }
}
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee(); { emp.Empid = 101; emp.Empname = "xyz"; emp.Emplocation = "Bangalore"; emp.Empsalary = 50000; };
IFormatter formattter = new BinaryFormatter();
Stream str = new FileStream(@"C:\Users\XXXX_XX\Documents\Testing\new.txt", FileMode.Open, FileAccess.Write);
formattter.Serialize(str, emp);
str.Close();
////De-Serlization
//IFormatter formatter = new BinaryFormatter();
//Stream str = new FileStream(@"C:\Users\XXXX_XX\Documents\Testing\new.txt", FileMode.Open, FileAccess.Read);
//Employee emp = formatter.Deserialize(str) as Employee;
//Console.WriteLine(emp.Empid+"\t"+emp.Empname+"\t"+emp.Emplocation+"\t"+emp.Empsalary);
}
}
}
推荐答案
ClassEmployee
根本不访问后备字段-
ClassEmployee
doesn''t access the backing field at all -
class Employee
{
public int Empid { get; set; }
public String Empname { get; set; }
public String Emplocation { get; set; }
private int Empsalary;
//This has no ties to the private field - the compiler will generate a (separate) backing field for it
//public int EmpSalary { get; set; }
//This actually uses the backing field
public int EmpSalary
{
get {return Empsalary; }
set { Empsalary = value;}
}
}
OT:同样,它调用字段Empsalary
会造成混淆,尤其是对于首字母大写.我个人会使用_empSalary
,尽管很多人会建议empSalary
OT: Also it calling the field Empsalary
is confusing, especially with the lead capital. Personally I''d use _empSalary
, though many people would suggest empSalary
这篇关于私有字段未发生二进制序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文