Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中创建对象和对象序列化#_C#_File_Class_Object - Fatal编程技术网

C# 在C中创建对象和对象序列化#

C# 在C中创建对象和对象序列化#,c#,file,class,object,C#,File,Class,Object,我是C#的初学者,我创建了一个Person类,其中包括更多变量和构造函数: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Contact { [Serializable()] //On peut le sérializer class Personne {

我是C#的初学者,我创建了一个Person类,其中包括更多变量和构造函数:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Contact
{
    [Serializable()] //On peut le sérializer    
    class Personne
    {
        //Constructeur
        public Personne(string prenom, string nom, int age, string dateNaissance, bool isMan, string notes, string pathImage, string mail, 
            string mail2, string tel, string telFix, string site, string rue, string ville, string numero, string codePostal, string departement)
        {
            Prenom = prenom;
            Nom = nom;
            Age = age;
            DateNaissance = dateNaissance;
            IsMan = isMan;
            Notes = notes;
            this.pathImage = pathImage;
            this.mail = mail;
            this.mail2 = mail2;
            this.tel = tel;
            this.telFix = telFix;
            this.site = site;
            this.rue = rue;
            this.ville = ville;
            this.numero = numero;
            this.codePostal = codePostal;
            this.departement = departement;
        }

        public override string ToString()
        {
            return base.ToString();
        }

        //Variables
        public string Prenom { get; set; }
        public string Nom { get; set; }
        public int Age { get; set; }
        public string DateNaissance { get; set; }
        public bool IsMan { get; set; }
        public string Notes { get; set; }
        public string pathImage { get; set; }
        public string mail { get; set; }
        public string mail2 { get; set; }
        public string tel { get; set; }
        public string telFix { get; set; }
        public string site { get; set; }
        public string rue { get; set; }
        public string ville { get; set; }
        public string numero { get; set; }
        public string codePostal { get; set; }
        public string departement { get; set; }
    }
}
当按下表单上的按钮时,此类对象的创建在此处完成:

private void Btn_valider_Click(object sender, EventArgs e)
{

                //Création de l'objet
                Personne contact = new Personne(Prenom, Nom, Age, dateNaissanceStr, isMan, notesStr, pathImage, mail, mail2, tel, telFix,
                    site, rue, ville, numero, codePostal, departement);

                //Sauvegarde l'objet
                Stream fichier = File.Create(@"contact.dat");
                BinaryFormatter serializer = new BinaryFormatter();
                serializer.Serialize(fichier, contact);
                fichier.Close();

                this.Close();
            }
            catch
            {
                MessageBox.Show("Erreur.");
            }
        }
    }
}

所以,正如我们所看到的,我创建了一个联系人对象(我创建了一个联系人管理器),但我希望有多个Person对象,因为我们不是只有一个联系人。但是如果我重新创建一个对象,我的serialiser只接受最后一个创建的对象,我希望恢复所有对象。

您可以创建一个
列表
,并使用
foreach
循环将它们保存在文件中。
您的“Btn\u valider\u Click”方法如下:

private void Btn_valider_Click(object sender, EventArgs e)
{
        var personList = new List<Personne>();

        //Création de l'objet
        Personne contact = new Personne(Prenom, Nom, Age, dateNaissanceStr, isMan, notesStr, pathImage, mail, mail2, tel, telFix,
            site, rue, ville, numero, codePostal, departement);

        personList.Add(contact);
        //Adding other persons


        foreach(var cont in personList)
        {
            //Sauvegarde l'objet
            Stream fichier = File.OpenWrite(@"contacts.dat");
            BinaryFormatter serializer = new BinaryFormatter();
            serializer.Serialize(fichier, cont);
            fichier.Close();
        }

        this.Close();
    }
    catch
    {
        MessageBox.Show("Erreur.");
    } 
}
private void Btn\u valider\u单击(对象发送方,事件参数e)
{
var personList=新列表();
//奥布杰特酒店
人员联系人=新人员(姓名、姓名、年龄、日期、isMan、notesStr、pathImage、mail、mail2、电话、telFix、,
地址,维尔街,编号,邮政编码,部门);
personList.Add(联系人);
//添加其他人
foreach(个人列表中的var cont)
{
//索维加德酒店
Stream fichier=File.OpenWrite(@“contacts.dat”);
BinaryFormatter序列化程序=新的BinaryFormatter();
serializer.Serialize(fichier,cont);
fichier.Close();
}
这个。关闭();
}
抓住
{
MessageBox.Show(“Erreur”);
} 
}
更新:
您应该考虑设计一个文件结构(合同如何放置在文件中)。我不确定您的序列化是否提供了从文件检索记录所需的所有数据。无论如何,现在可以写入文件了。

您可以创建一个
列表
,并使用
foreach
循环将它们保存在文件中。
您的“Btn\u valider\u Click”方法如下:

private void Btn_valider_Click(object sender, EventArgs e)
{
        var personList = new List<Personne>();

        //Création de l'objet
        Personne contact = new Personne(Prenom, Nom, Age, dateNaissanceStr, isMan, notesStr, pathImage, mail, mail2, tel, telFix,
            site, rue, ville, numero, codePostal, departement);

        personList.Add(contact);
        //Adding other persons


        foreach(var cont in personList)
        {
            //Sauvegarde l'objet
            Stream fichier = File.OpenWrite(@"contacts.dat");
            BinaryFormatter serializer = new BinaryFormatter();
            serializer.Serialize(fichier, cont);
            fichier.Close();
        }

        this.Close();
    }
    catch
    {
        MessageBox.Show("Erreur.");
    } 
}
private void Btn\u valider\u单击(对象发送方,事件参数e)
{
var personList=新列表();
//奥布杰特酒店
人员联系人=新人员(姓名、姓名、年龄、日期、isMan、notesStr、pathImage、mail、mail2、电话、telFix、,
地址,维尔街,编号,邮政编码,部门);
personList.Add(联系人);
//添加其他人
foreach(个人列表中的var cont)
{
//索维加德酒店
Stream fichier=File.OpenWrite(@“contacts.dat”);
BinaryFormatter序列化程序=新的BinaryFormatter();
serializer.Serialize(fichier,cont);
fichier.Close();
}
这个。关闭();
}
抓住
{
MessageBox.Show(“Erreur”);
} 
}
更新:
您应该考虑设计一个文件结构(合同如何放置在文件中)。我不确定您的序列化是否提供了从文件检索记录所需的所有数据。无论如何,现在对文件的写入应该是正确的。

< P>关于我的评论,这里有几件事要考虑(因此它的几个实现与这些考虑有关)。
这个答案将对
列表
类型使用反序列化和序列化,并在序列化之前有条件检查文件是否存在

模拟数据 样品
publicstaticvoid按钮\u单击(对象发送者、事件args args)
{
var人员=新人员
{
Prenom=“Prenom”,
Nom=“Nom”,
年龄=21岁,
DateNaissance=“DateNaissance”,
IsMan=true,
Notes=“Notes”,
pathImage=“pathImage”,
mail=“mail”,
mail2=“mail2”,
tel=“tel”,
telFix=“telFix”,
site=“site”,
rue=“rue”,
ville=“ville”,
numero=“numero”,
codePostal=“codePostal”,
department=“department”
};
SeralizePersoneeDataFile(个人);
}
公共静态无效SeralizePersoneeDataFile(Personee Personee)
{
SeralizePersoneeDataFile(新人员[]{Personee});
}
公共静态无效SeralizePersoneeDataFile(IEnumerable Persones)
{
var personeeDataList=(File.Exists(FilePath))
?反序列化PersoneDataFile()
:新列表();
personeeDataList.AddRange(personees);
使用(FileStream fichier=File.OpenWrite(FilePath))
{
BinaryFormatter序列化程序=新的BinaryFormatter();
serializer.Serialize(fichier,personeeDataList);
}
}
公共静态列表反序列化PersoneDataFile()
{
使用(FileStream fichier=File.OpenRead(FilePath))
{
BinaryFormatter序列化程序=新的BinaryFormatter();
返回(序列化程序.反序列化(fichier)为列表);
}
}

这里需要在序列化之前进行反序列化,因为此序列化实现将整个内容写入文件(不追加)。也就是说,如果你在数据文件中有100个联系人,然后以这种方式写1条记录,它将清除文件,只保存1。

< P>关于我的评论,这里有几件事要考虑(因此它的几个实现与这些考虑有关)。
这个答案将对
列表
类型使用反序列化和序列化,并在序列化之前有条件检查文件是否存在

模拟数据 样品
publicstaticvoid按钮\u单击(对象发送者、事件args args)
{
var人员=新人员
{
Prenom=“Prenom”,
Nom=“Nom”,
年龄=21岁,
DateNaissance=“DateNaissance”,
IsMan=true,
Notes=“Notes”,
pathImage=“pathImage”,
mail=“mail”,
mail2=“mail2”,
tel=“tel”,
telFix=“telFix”,
site=“site”,
rue=“rue”,
ville=“ville”,
numero=“numero”,
codePostal=“codePostal”,
department=“department”
};
SeralizePersoneeDataFile(个人
public static void Button_Click(object sender, EventArgs args)
{
    var personee = new Personee
    {
        Prenom = "Prenom",
        Nom = "Nom",
        Age = 21,
        DateNaissance = "DateNaissance",
        IsMan = true,
        Notes = "Notes",
        pathImage = "pathImage",
        mail = "mail",
        mail2 = "mail2",
        tel = "tel",
        telFix = "telFix",
        site = "site",
        rue = "rue",
        ville = "ville",
        numero = "numero",
        codePostal = "codePostal",
        departement = "department"
    };

    SeralizePersoneeDataFile(personee);
}

public static void SeralizePersoneeDataFile(Personee personee)
{
    SeralizePersoneeDataFile(new Personee[] { personee });
}

public static void SeralizePersoneeDataFile(IEnumerable<Personee> personees)
{
    var personeeDataList = (File.Exists(FilePath))
        ? DeseralizePersoneeDataFile()
        : new List<Personee>();

    personeeDataList.AddRange(personees);

    using (FileStream fichier = File.OpenWrite(FilePath))
    {
        BinaryFormatter serializer = new BinaryFormatter();
        serializer.Serialize(fichier, personeeDataList);
    }
}

public static List<Personee> DeseralizePersoneeDataFile()
{
    using (FileStream fichier = File.OpenRead(FilePath))
    {
        BinaryFormatter serializer = new BinaryFormatter();
        return (serializer.Deserialize(fichier) as List<Personee>);
    }
}
public int length, breadth; 

// Parameterized Constructor 
// User defined 
public Rectangle(int l, int b) 
{ 
    length = l; 
    breadth = b; 
} 

// Method to Calculate Area 
// of the rectangle 
public int Area() 
{ 
    return length * breadth; 
} 
// Main Method 
static void Main(string[] args) 
{ 
    // Creating an object using 'new' 
    // Calling the parameterized constructor 
    // With parameters 10 and 12 
    Rectangle rect1 = new Rectangle(10, 12); 

    // To display are of the Rectangle 
    int area = rect1.Area(); 
    Console.WriteLine("The area of the"+ 
               " Rectangle is " + area); 
}