我在学校的学习项目Cinema工作。我们必须使用二进制文件而不是数据库。我有以下主要模型:用户,电影,房间,票证,投影 ... 票证和投影包含id
以及电影,会议室的完整对象(用户 Ticket )。
电影,会议室和用户未在投影 / 故障单中序列化为对象,就像id
一样。因此,在调用 Property 之后,ex。 ticketObj.Movie
,它使用id
初始化该电影,该票证有。
有一个问题。一切都适用于投影。它可以毫无问题地序列化/反序列化 Movie 和 Room 。但是,在 Ticket ,它不会序列化用户。它只是留空,如null
。
我测试了我所知道的一切。我检查并比较了类,用户具有相同的属性(getters),如 Movie 或 Room 。我尝试了很多调试工作,并且在序列化方法之前存在userObj
。但是,它不会以某种方式序列化它。我需要注意,用户有[Serializable]
符号。
还有一件事,我做了 Seeder ,它为所有模型创建初始对象并保存。所以,一切都在运作,它将一切都很好地序列化。但是,当我尝试在“运行时”中对其进行序列化时,它将无法正常工作......
我请求帮助,我在此失去了两天。 如果需要,我会发布消息来源。
编辑:
有代码:
我使用这些方法进行读/存储:
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
/* Writing list to binary file, object by object */
public static void WriteListToBinaryFile<T>(string filePath, List<T> listToWrite, bool append = false)
{
for ( int i = 0 ; i < listToWrite.Count ; i++ )
{
if ( append == false)
{
if ( i == 0 )
WriteToBinaryFile<T>( filePath , listToWrite [ i ] , false );
else
WriteToBinaryFile<T>( filePath , listToWrite[i] , true );
}
else
WriteToBinaryFile<T>( filePath , listToWrite[i] , append );
}
}
/**
* Deserialization of all object, as list
* */
public static List<T> ReadAllObjectFromFile<T>(string path)
{
if ( !isFileEmpty( path ) )
{
long position = 0;
List<T> list = new List<T> ( );
BinaryFormatter formatter = new BinaryFormatter ( );
using ( FileStream stream = new FileStream ( path , FileMode.OpenOrCreate, FileAccess.Read ) )
{
while ( position != stream.Length )
{
stream.Seek( position , SeekOrigin.Begin );
list.Add( ( T )formatter.Deserialize( stream ) );
position = stream.Position;
}
}
return list;
}
return null;
}`
[Serializable]
public class Ticket
{
private int _ticketId;
private float _price;
private int _row;
private int _seat;
private int _projectionId;
private int _userId;
[NonSerialized]
private Projection _projection;
[NonSerialized]
private User _buyer;
private static List<int> list_of_ids = InitializeIdList();
public Ticket ()
{
this._ticketId = Metode.GetId(ref list_of_ids);
this._projection = null;
this._price = 0.0F;
this._row = this._seat = 0;
this._buyer = null;
this._buyer_id = 0;
this._projection_id = 0;
}
public Ticket ( Projection projection, User buyer, float price, int row, int seat )
{
this._ticketId = Methods.GetId(ref lista_id);
this._projection = projection;
this._buyer = buyer;
this._price = price;
this._row = row;
this._seat = seat;
this._buyer_id = buyer.UserId;
this._projection_id = Projection.ProjectionId;
}
public Ticket ( int projection_id, int buyer_id, float price, int row, int seat )
{
this._ticketId = Methods.GetId(ref lista_id);
this._projection = Projection.ById(Projection_id);
this._buyer = User.ById(buyer_id);
this._price = price;
this._row = row;
this._seat = seat;
this._buyer_id = buyer_id;
this._projection_id = projection_id;
}
public int TicketId
{
get { return this._ticketId; }
}
public Projection Projection
{
get
{
if ( this._projection == null && this._projection_id != 0 )
{
this._projection = Projection.ById( _projection_id );
}
return this._projection;
}
set
{
_projection = value;
_projection_id = value.ProjectionId;
}
}
public int Row
{
get { return this._row; }
}
public int Seat
{
get { return this._seat; }
}
public float Price
{
get { return this._price; }
set { _price = value; }
}
public User Buyer
{
get
{
if ( this._buyer == null && this._buyer_id != 0 )
{
this._buyer = User.ById( _buyer_id );
}
return this._buyer;
}
set
{
_buyer = value;
_buyer_id = value.UserId;
}
}
public static List<Ticket> All()
{
List<Ticket> list = (List<Ticket>)
Seralization.ReadAllObjectFromFile<Ticket>(Seralization.TiFile);
// List<Projection> listProj = Projection.All();
// List<User> listUsers = User.All();
//
// for ( int i = 0 ; i < list.Count -1 ; i++ )
// {
// //Console.WriteLine( "buyer id: " + list[i]._buyer_id);
//
// User k = listUsers.Find( x => x.UserId == list[i]._buyer_id );
//
// list [ i ]._buyer = k;
// list [ i ]._projection = listProj.Find( x => x.ProjectionId == list[i]._projection_id );
//
// //Console.WriteLine("\nbuyer: " + list[i]._buyer);
// //Console.WriteLine("\nProjection: " + list[i]._projection);
//
// }
return list;
}
public static Ticket ById(int id)
{
List<Ticket> allTickets = Sve();
foreach (Ticket k in allTickets)
{
if (k.TicketId == id)
{
return k;
}
}
return null;
}
public void Save()
{
List<Ticket> allTickets = Sve();
if ( allTickets != null )
{
for ( int i = 0; i < allTickets.Count-1; i++ )
{
if ( allTickets[i].TicketId == this._ticketId )
{
allTickets [ i ] = this;
Serialization.WriteListToBinaryFile<Ticket>( Serialization.TiFile , allTickets , false );
Console.WriteLine( "You have successfully saved ticket!" );
return;
}
}
}
else
{
Serialization.WriteToBinaryFile<Ticket>(Serialization.TiFile, this, true);
}
Console.WriteLine("You have successfully saved ticket!");
}
/* Save Ticket */
public static void SaveTicket( Projection projection, User buyer, float price, int row, int seat )
{
List<Ticket> allTickets = Ticket.Sve();
Ticket Ticket = new Ticket(projection.ProjectionId, buyer.UserId,price,row,seat);
allTickets.Add( Ticket );
Serialization.WriteListToBinaryFile<Ticket>( Serialization.TiFile , allTickets , false );
Console.WriteLine("Ticket is saved!");
}
public override string ToString()
{
return String.Format("[ id:{0}, Projection{1}, buyer: {2}, row:{3}, seat:{4}, price:{5} ]",
_ticketId, this.Projection, this.Buyer, _row, _seat, _price );
}
public bool Equals(Ticket k2)
{
if( this._projection == k2.Projection &&
this._row == k2.Row &&
this._seat == k2.Seat &&
this._price == k2.Price &&
this._buyer == k2.Buyer
)
return true;
return false;
}
private static List<int> InitializeIdList()
{
List<Ticket> list = Sve();
List<int> list_id = new List<int> ( );
if ( list != null )
{
foreach ( Ticket k in list )
{
list_id.Add( k.TicketId );
}
}
return list_id;
}
}
}
`
[Serializable]
public class Projection
{
private int _projectionId;
private string _time;
private int _movie_id;
private int _room_id;
[NonSerialized]
private Movie _movie;
[NonSerialized]
private Room _room;
private static List<int> list_id = InitializeIdList();
public Projection ()
{
this._projectionId = Methods.GetId(ref list_id);
this._room = null;
this._movie = null;
this._time = DateTime.Now.ToString("f");
this._movie_id = 0;
this._room_id = 0;
}
public Projection( Movie movie, Room room, string time )
{
this._projectionId = Methods.GetId(ref list_id);
this._movie = movie;
this._room = room;
this._time = time;
this._movie_id = movie.MovieId;
this._room_id = room.RoomId;
}
public Projection( int movie_id, int room_id, string time )
{
this._movie_id = movie_id;
this._room_id = room_id;
this._projectionId = Methods.GetId(ref list_id);
this._movie = Movie.ById(movie_id);
this._room = Room.ById(room_id);
this._time = time;
}
public int ProjectionId
{
get { return this._projectionId; }
}
public Movie Movie
{
get
{
if ( this._movie == null && this._movie_id != 0 )
{
this._movie = Movie.ById( _movie_id );
}
return this._movie;
}
set
{
_movie = value;
_movie_id = value.MovieId;
}
}
public Room Room
{
get
{
if ( this._room == null && this._room_id != 0 )
{
this._room = Room.ById( _room_id );
}
return this._room;
}
set
{
_room = value;
_room_id = value.RoomId;
}
}
public string Time
{
get { return this._time; }
set { _time = value; }
}
/**
* Methods
* */
public static List<Projection> All()
{
List<Projection> list = (List<Projection>) Serialization.ReadAllObjectFromFile<Projection>(Serialization.ProjFile);
// List<Movie> allMovies = Movie.All();
// List<Room> allRooms = Room.All();
//
//
// for ( int i = 0 ; i < list.Count -1 ; i++ )
// {
// list [ i ]._movie = allMovies.Find( (x ) => list [ i ]._movie_id == x.MovieId );
// list [ i ]._room = allRooms.Find( (x ) => list [ i ]._room_id == x.RoomId );
//
// }
return list;
}
public static Projection ById(int id)
{
List<Projection> allProjections = All();
foreach (Projection p in allProjections)
{
if (p.ProjectionId == id)
{
return p;
}
}
return null;
}
// public static void SaveProjection( Movie movie, Room room, DateTime time )
// {
// List<Projection> allProjections = All();
//
// Projection Projection = new Projection(movie, room, time);
//
// Serialization.WriteToBinaryFile<Projection>(Serialization.ProDat, projection, true);
// Console.WriteLine("Projection is successfully saved!");
// }
public void Save()
{
List<Projection> allProjections = All();
if ( allProjections != null )
{
foreach ( var item in allProjections )
{
if ( item.ProjectionId == this._projectionId )
{
allProjections.Remove( item );
allProjections.Add( this );
//allProjections [ i ] = this;
Serialization.WriteListToBinaryFile<Projection>( Serialization.ProjFile , allProjections , false );
Console.WriteLine( "Projection is successfully saved!" );
return;
}
}
}
else
{
Serialization.WriteToBinaryFile<Projection>(Serialization.ProjFile, this, true);
}
Console.WriteLine("Projection is successfully saved!");
}
public static void SaveProjection( Projection Projection )
{
List<Projection> allProjections = All();
foreach (Projection p in allProjections)
{
if (p == Projection)
{
Console.WriteLine("Projection is already exist!");
return;
}
}
Serialization.WriteToBinaryFile<Projection>(Serialization.ProjFile, Projection, true);
Console.WriteLine("Projection is successfully saved!");
}
public override string ToString()
{
return String.Format("[ id:{0}, Movie:{1}, Room:{2}, Time:{3} ]",
_projectionId, this.Movie, this.Room, _time );
}
public bool Equals(Projection p2)
{
if( this._time == p2.Time &&
this._room == p2.Room &&
this._movie == p2.Movie
)
return true;
return false;
}
private static List<int> InitializeIdList()
{
List<Projection> list = All();
List<int> list_id = new List<int> ( );
if ( list != null )
{
foreach ( Projection p in list )
{
list_id.Add( p.ProjectionId );
}
}
return list_id;
}
}
}
[Serializable]
public class Movie
{
private int _movieId;
private string _title;
private Genre _genre;
private string _about;
private float _rate;
private static List<int> list_id = InitializeIdList();
/**
* Constructors
* */
public Movie()
{
this._movieId = Methods.GetId(ref list_id);
this._title = "";
this._about = "";
this._rate = 0.0F;
this._genre = Genre.akcija;
}
public Movie(string title, Genre z, string about, float rate)
{
this._movieId = Methods.GetId(ref list_id);
this._title = title;
this._genre = z;
this._about = about;
this._rate = rate;
}
public int MovieId
{
get { return this._movieId; }
}
public string Title
{
get { return this._title; }
set { _title = value; }
}
public Genre GetGenre()
{
return this._genre;
}
public void SetGenre( Genre genre)
{
this._genre = genre;
}
public string About
{
get { return this._about; }
set { _about = value; }
}
public float Rate
{
get { return this._rate; }
set { _rate = value; }
}
public static List<Movie> All()
{
List<Movie> lista = (List<Movie>) Serialization.ReadAllObjectFromFile<Movie>(Serialization.MovFile);
return lista;
}
public static Movie ById(int id)
{
if (list_id.Contains(id))
{
List<Movie> allMovies = All();
foreach (Movie f in allMovies)
{
if (f.MovieId == id)
{
return f;
}
}
}
else
{
Console.WriteLine("Movie sa id:{0} ne postoji!", id);
}
return null;
}
public static List<Movie> ByTitle(string title)
{
List<Movie> allMovies = All();
List<Movie> whoseContainsTitle = new List<Movie>();
foreach (Movie f in allMovies)
{
if (f.Title.ToLower() == title.ToLower())
{
whoseContainsTitle.Add(f);
}
else if (f.Title.ToLower().Contains(title.ToLower()))
{
whoseContainsTitle.Add(f);
}
}
return whoseContainsTitle;
}
public static List<Movie> ByGenre(Genre genre)
{
List<Movie> allMovies = All();
List<Movie> allMoviesFromGenre = new List<Movie>();
foreach (Movie f in allMovies)
{
if (f.GetGenre() == genre)
{
allMoviesFromGenre.Add(f);
}
}
return allMoviesFromGenre;
}
// public static void SaveMovie(string title, Genre z, string about, float rate)
// {
// List<Movie> allMovies = All();
//
// foreach (Movie f in allMovies)
// {
// if (f.Title.ToLower() == title)
// {
// Console.WriteLine("That movie already exist!");
// }
// }
// Movie film = new Movie(title, z, about, rate);
//
// Serialization.WriteToBinaryFile<Movie>(Serialization.MovFile, film, true);
// Console.WriteLine("Movie is successfully saved!");
// }
public void Save()
{
List<Movie> allMovies = All();
if ( allMovies != null )
{
foreach ( var item in allMovies )
{
if ( item.MovieId == this._movieId )
{
allMovies.Remove( item );
allMovies.Add( this );
Serialization.WriteListToBinaryFile<Movie>( Serialization.MovFile , allMovies , false );
Console.WriteLine( "Movie is successfully saved!" );
return;
}
}
}
else
{
Serialization.WriteToBinaryFile<Movie>(Serialization.MovFile, this, true);
}
Console.WriteLine("Movie is successfully saved!!");
}
public static void SaveMovie( Movie movie )
{
List<Movie> allMovies = All();
foreach (Movie f in allMovies)
{
if (f == movie)
{
Console.WriteLine("That movie already exist!");
return;
}
}
Serialization.WriteToBinaryFile<Movie>(Serialization.MovFile, film, true);
Console.WriteLine("Movie is successfully saved!");
}
public override string ToString()
{
return String.Format("[ id:{0}, title:{1}, genre:{2}, about:{3}, rate:{4} ]",
_movieId, _title, _genre.ToString(), _about, _rate);
}
public bool Equals(Movie f2)
{
if( this._genre == f2.GetGenre() &&
this._rate == f2.Rate &&
this._about == f2.About &&
this._title == f2.Title
)
return true;
return false;
}
private static List<int> InitializeIdList()
{
List<Movie> list = All();
List<int> list_id = new List<int> ( );
if ( list != null )
{
foreach ( Movie f in list )
{
list_id.Add( f.MovieId );
}
}
return list_id;
}
}
}
[Serializable]
public class User
{
private int _userId;
private string _username;
private string _password;
private int _type;
private string _nameAndSurname;
private static List<int> list_id = InitializeIdList();
public const int ADMIN = 1;
public const int SPEC = 2;
public User ()
{
this._userId = Methods.GetId(ref list_id);
this._nameAndSurname = "";
this._username = "";
this._password = "";
}
public User (string username, string password, int type, string nameAndSurname)
{
this._userId = Methods.GetId(ref list_id);
this._username = username;
this._password = password;
this._type = type;
this._nameAndSurname = nameAndSurname;
}
public int UserId {
get {
return this._userId;
}
}
public string Username {
get {
return this._username;
}
set {
_username = value;
}
}
public string Password {
get {
return this._password;
}
set {
_password = value;
}
}
public int Type {
get {
return this._type;
}
set {
_type = value;
}
}
public string NameAndSurname {
get {
return this._nameAndSurname;
}
set {
_nameAndSurname = value;
}
}
public User Clone()
{
return new User ( this._username, this._password, this._type, this._nameAndSurname);
}
public static bool proveriDaLiPostoji(string username, string password, out User k)
{
List<User> allUsers = All();
foreach(User user in allUsers)
{
if (String.Compare(user.Username.Trim(),username,false) == 0 && String.Compare(user.Password.Trim(),password,false) == 0 )
{
k = user.Clone ();
return true;
}
}
k = null;
return false;
}
public static User LogIn(string username, string password)
{
User k = null;
if (!isExist (username, password,out k))
{
Console.WriteLine("User with that credentials doesn't exist!");
}
Console.WriteLine("You have successfully logged in!");
return k;
}
public override string ToString ()
{
return string.Format ("[User: _userId={0}, _username={1}, _password={2}, _type={3}, _nameAndSurname={4}]",
_userId, _username, _password, _type, _nameAndSurname);
}
public bool Equals(User k2)
{
if( this._type == k2.Type &&
this._password == k2.Password &&
this._nameAndSurname == k2.NameAndSurname &&
this._username == k2.Username
)
return true;
return false;
}
public static List<User> All()
{
List<User> list = (List<User>)Serialization.ReadAllObjectFromFile<User>( Serialization.UsrFile );
return list;
}
public static User ById(int id)
{
List<User> allUsers = All();
foreach ( User k in allUsers)
{
if ( k.UserId == id )
{
return k;
}
}
return null;
}
// public static void SaveUser(string username, string password, int type, string nameAndSurname)
// {
// List<User> allUsers = All();
//
// foreach ( User k in allUsers )
// {
// if ( k.Username.ToLower() == Username )
// {
// Console.WriteLine("User with that username already exist!");
// }
// }
// User user = new User ( username, password, type, nameAndSurname );
//
// Serialization.WriteToBinaryFile<User>( Serialization.UsrFile , user , true );
// Console.WriteLine("User successfully saved!");
//
// }
public void Save()
{
List<User> allUsers = All();
if ( allUsers != null )
{
foreach ( var item in allUsers )
{
if (item.UserId == this._userId )
{
allUsers.Remove( item );
allUsers.Add( this );
Serialization.WriteListToBinaryFile<User>( Serialization.UsrFile , allUsers , false );
Console.WriteLine( "User is successfully saved!" );
return;
}
}
}
else
{
Serialization.WriteToBinaryFile<User>(Serialization.UsrFile, this, true);
}
Console.WriteLine("User is successfully saved!");
}
public static void SaveUser( User user )
{
List<User> allUsers = All();
foreach ( User k in allUsers )
{
if ( k == user )
{
Console.WriteLine("That user is already exist!");
return;
}
}
Serialization.WriteToBinaryFile<User>( Serialization.UsrFile , user , true );
Console.WriteLine("User is successfully saved!");
}
private static List<int> InitializeIdList()
{
List<User> list = All();
List<int> list_id = new List<int> ( );
if ( lista != null )
{
foreach ( User k in list )
{
list_id.Add( k.UserId );
}
}
return list_id;
}
}
}
Seeder的代码有效:https://pastebin.com/6szcT5Ke
View中的代码不起作用:https://pastebin.com/Wh8KfSN3
如果需要,我会发布其他内容。