【问题标题】:How to save/write Task with different attributes如何保存/写入具有不同属性的任务
【发布时间】:2021-12-17 23:54:04
【问题描述】:

我正在尝试构建一个更高级的 ToDoList-Console 程序。我正在学习序列化,但我似乎不明白如何:

  • 实现 2 种任务
  • 将它们保存在文件中(不必是 json)
  • 在考虑任务类型的同时读取文件

我的目标是拥有 2 种方法:task1 和 task2。 Task1 是主要任务,task2 是任务的子任务,可以在控制台中使用 \t 进行可视化。 这是我当前的代码,它只是将任务保存为字符串,没有任何复杂性。

public class TodoItem
    {
        public string Description { get; set; }
        public DateTime? DueOn { get; set; }

        public override string ToString()
        {
            return $"{this.Description}";
        }
    }

    internal static class Program
    {
        static private readonly string _saveFileName = "todo.json";
        static void Main()
        {
            {
                // An example list containing 2 items
                List<TodoItem> items = new List<TodoItem> {
                new TodoItem { Description = "Feed the dog" },
                new TodoItem { Description = "Buy groceries" /*, DueOn = new DateTime(2021, 9, 30, 16, 0, 0)*/ }
            };
                // Serialize it to JSON
                string json = JsonSerializer.Serialize(items, new JsonSerializerOptions() { WriteIndented = true });

                // Save it to a file
                File.WriteAllText(_saveFileName, json);
            }

            // Loading list
            {
                string json = File.ReadAllText(_saveFileName);

                List<TodoItem> items = JsonSerializer.Deserialize<List<TodoItem>>(json);

                // Loading items
                foreach (var todo in items)
                    Console.WriteLine(todo);
            }

        }```

【问题讨论】:

    标签: c# serialization


    【解决方案1】:

    您可以使用inheritance 来实现两种类型的任务。

    你的其他目标似乎已经奏效了 :)

    这是一个例子:

    public abstract class TaskBase
    {
        public string Description { get; set; }
        
        public DateTime? DueOn { get; set; }
    
        public override string ToString()
        {
            return $"{Description}";
        }
    }
    
    public class MainTask : TaskBase
    {
        public SubTask? SubTask { get; set; }
    
        public override string ToString()
        {
            if (SubTask is not null)
            {
                return $"{Description}{Environment.NewLine}\t{SubTask}";
            }
            else
            {
                return base.ToString();
            }
        }
    }
    
    public class SubTask : TaskBase {}
    
    static class Program
    {
        private const string _saveFileName = "todo.json";
    
        static void Main()
        {
            {
                // An example list containing 2 items
                List<MainTask> items = new List<MainTask> 
                {
                    new MainTask { Description = "Feed the dog" },
                    new MainTask { Description = "Buy groceries", SubTask = new SubTask { Description = "Food" } }
                };
    
                // Serialize it to JSON
                string json = JsonSerializer.Serialize(items, new JsonSerializerOptions() { WriteIndented = true });
    
                // Save it to a file
                File.WriteAllText(_saveFileName, json);
            }
    
            // Loading list
            {
                string json = File.ReadAllText(_saveFileName);
    
                List<MainTask> items = JsonSerializer.Deserialize<List<MainTask>>(json);
    
                // Loading items
                foreach (var todo in items)
                    Console.WriteLine(todo);
            }
    
        }
    }
    

    【讨论】:

    • 您好,感谢您的帮助。它完美地工作并且不会增加太多的复杂性。我是一个初学者,之前没有做过任何序列化或 json 的事情,所以我什么都不懂。 “:”在这种情况下做了什么,添加“public class SubTask:TaskBase {}”的原因或作用是什么?非常感谢,现在我知道我要注意什么了:)
    • 没什么好羞愧的 ;) 我假设您知道面向对象编程的继承概念。如果不是,你真的应该阅读我在我的答案 (docs.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/…) 中链接的关于继承的文章,因为在 Stack Overflow 的评论部分用 500 个字符来描述并不是一个简单的概念。 MainTask : TaskBase 之间的 :MainTask 继承 TaskBase 的所有功能的 C# 语法。这同样适用于SubTask,因此MainTaskSubTask 的类型为TaskBase。玩得开心^^
    猜你喜欢
    • 2021-05-11
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 2015-02-06
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多