繁体   English   中英

在文件 C# 之间共享一个 object

[英]Sharing an object between files C#

我不得不说我是 oop 的新手。我有一个 .NET 框架应用程序和 MainForm.cs class。我还在 Book.cs class 中创建了一个 object 'Book':

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

在 MainForm 中,我创建了一本书并使用这本书。 之后我需要在 Program.cs 文件中使用这本书。 我该怎么做? 以前我在 C++ 工作,我知道 extern 关键字(在 C++ 中)。 C# 中有类似的东西吗?

我来猜

第一变

class Book
{

public class Book
{

因为它需要在它声明的文件之外

现在在 Program.cs 中做

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

我知道这几乎肯定不是你想要的,我敢打赌你已经有一个或 2 个书籍实例,但你没有说它们是在哪里以及如何创建或存储的(我不是说在数据库中,我只是说'它是一个列表,一个数组,只是一个变量...')

首先,为什么要将代码放在Program.cs文件中? 您在项目中添加的每个Form本身就是一个Class ,您可以在任何Form class 中执行所有Book.cs操作。

暂无
暂无

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

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