简体   繁体   中英

Sharing an object between files C#

I have to say that I'm a newbie in oop. I have a .NET Framework app with a MainForm.cs class. I also created an object 'Book' in Book.cs class:

namespace SimpleAudiobookPlayer.Model
{
    class Book
    {
        public string Title
        {
            get; set;
        }
        public string Author
        {
            get; set;
        }
        public int Chapters
        {
            get; set;
        }
        public string Path
        {
            get; set;
        }
        public int LastReadChapter
        {
            get; set;
        }
        public TimeSpan EndTime
        {
            get; set;
        }
        public List<string> ChaptersPaths
        {
            get; set;
        }

        public Book(string title, string author, int chapters, string path, int lastReadChapter, TimeSpan endTime, List<string> chaptersPaths)
        {
            this.Title = title;
            this.Author = author;
            this.Chapters = chapters;
            this.Path = path;
            this.LastReadChapter = lastReadChapter;
            this.EndTime = endTime;
            this.ChaptersPaths = chaptersPaths;
        }
    }
}

In MainForm I create a Book and I work with this Book. After that I need to use this Book in Program.cs file. How can I do it? Previously I worked in C++ and I know about extern keyword (in c++). Is in C# something simmilar?

I am going to guess

Firt change

class Book
{

to

public class Book
{

Becuase its needed outside the file it declared in

Now in Program.cs do

 var Book = new Book("title", "author", .....);

I know this is almost certainly not what you want, I bet you already have a book instance or 2 but you have not said where or how they are created or stored (I dont mean in a database, i just mean 'is it a list, an array, just a sigle variable...')

Firstly, why would you want to put code in Program.cs file? Every Form you add in your project is in itself a Class and you can perform all your Book.cs manipulations in any Form class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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