简体   繁体   English

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

[英]Creating objects and object serialization in C#

I'm a beginner in C# and I created a Person class, which includes more variable and a constructor:我是 C# 的初学者,我创建了一个 Person class,其中包括更多变量和一个构造函数:

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; }
    }
}

The creation of an object of this class is done here, when pressing a button on my form:当按下我的表单上的按钮时,这里完成了 class 的 object 的创建:

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.");
            }
        }
    }
}

So, as we can see, I create a contact object (I make a contact manager), but I would like there to be several Person objects, because we don't have only one contact.因此,正如我们所见,我创建了一个联系人 object(我创建了一个联系人管理器),但我希望有多个 Person 对象,因为我们不只有一个联系人。 But if I recreate an object, my serialiser only takes the last one created and I would like to recover ALL the objects.但是如果我重新创建一个 object,我的序列化器只需要最后一个创建的,我想恢复所有对象。

You can create a List<Personne> and save them in the file using a foreach loop.您可以创建一个List<Personne>并使用foreach循环将它们保存在文件中。
Your "Btn_valider_Click" method will be something like this:您的“Btn_valider_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.");
    } 
}

UPDATE: You should consider designing a file structure (how contracts are placed in the file).更新:您应该考虑设计文件结构(合同如何放置在文件中)。 I am not sure that your serialization provides all the data which is needed for retrieving records from the file.我不确定您的序列化是否提供了从文件中检索记录所需的所有数据。 Anyway, writing to the file should be okay now.无论如何,现在写入文件应该没问题。

in regards to my comment, there are several thing to consider here (and thus several implementations at it relates to those considerations).关于我的评论,这里有几件事需要考虑(因此它的几个实现与这些考虑有关)。


This answer is going to use Deserialization and Serialization on a List<Personee> type with conditional checks on whether the file exists before serializing.这个答案将在List<Personee>类型上使用反序列化和序列化,并在序列化之前有条件地检查文件是否存在。

Mock Data模拟数据

[Serializable]
public class Personee
{
    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; }
}

public static string FilePath = @"contacts.dat";

public static void RunSample()
{
    Button_Click(null, null);
}

Sample样本

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>);
    }
}

The Deserialization before serialization is necessary here because this serialization implementation writes the entire contents to the file (does not append).这里需要序列化之前的反序列化,因为这个序列化实现将整个内容写入文件(不追加)。 That is, if you have 100 contacts in the data file, and then just write 1 record in this manner, it will clear the file and only save the 1.也就是说,如果你的数据文件中有100个联系人,然后只用这种方式写入1条记录,就会清空文件,只保存1条。

Try This尝试这个

using System;使用系统;

namespace NewOperator {命名空间 NewOperator {

class Rectangle { class 矩形 {

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; 
} 

} }

// Driver Class class Program { // 驱动 Class class 程序 {

// 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); 
} 

} } } }

I found it here: https://www.geeksforgeeks.org/different-ways-to-create-an-object-in-c-sharp/我在这里找到它: https://www.geeksforgeeks.org/different-ways-to-create-an-object-in-c-sharp/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM