【问题标题】:Storing/Saving a Method and later re-calling it存储/保存方法并稍后重新调用它
【发布时间】:2021-12-02 22:45:01
【问题描述】:

我目前正在尝试制作的是一个库存系统。我想知道我是否可以存储当前方法然后打开清单,当我在那里完成时,重新打开/调用之前运行的方法。

【问题讨论】:

    标签: c# user-interface methods inventory


    【解决方案1】:

    你没有提供太多信息,但我可以告诉你不想存储方法,你想存储一个对象。

    对象是类的实例。根据您拥有的类的类型,您可以创建一个类的多个实例并在您的应用程序中多次实例化它们。或者,您可以创建在整个应用程序/游戏中使用的对象的单个实例。

    从听起来,您想使用一个单例类来保留用户库存的当前值。因此,如果您在程序的某个部分与清单类进行交互,您希望随后查看并与存储在程序另一部分的单例中的相同先前修改的值进行交互。

    我无法为您的问题提供具体答案,但您的用例可能的 Singleton 类看起来像这样;

    public sealed class Inventory
    {
        private static readonly Inventoryinstance = new Inventory();
    
        // Explicit static constructor to tell C# compiler
        // not to mark type as before field init
        static Inventory()
        {
        }
    
        private Inventory()
        {
            // optionally, pre-populate with data stored in database when constructed
        }
    
        public static Inventory Instance
        {
            get
            {
                return instance;
            }
        }
    
        public List<InventoryItem> InventoryItems { get; set; } = new List<InventoryItem>();
    
        public void AddItemToInventory(InventoryItem item) {
            InventoryItems.Add(item);
        }
    
        public void RemoveItemFromInventory(InventoryItem item) {
            InventoryItems.Remove(item);
        }
    }
    

    您可以参考本站-https://csharpindepth.com/articles/singleton

    如果您有一个使用 DI 的应用程序,您可以创建可注入其他应用程序类的单例实例。这是一种更好的处理单例的方法,因为它们由 IoC 系统处理,而不是被设置为静态以供整个应用程序访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-24
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多