如何使类列表可公开访问

本文关键字:访问 何使类 列表 | 更新日期: 2023-09-27 18:03:41

我想要一个像下面这样的对象列表,可以从任何地方访问,我理解的"单例"类。

public class Car
{
    public string Name;
    public string Color;
    public int Value;
}

List<Vehicle> carList = new List<Vehicle>();
Car jeep = new Car();
jeep.Name = "Jeep";
jeep.Color = "Red";
jeep.Value = 20000;
Vehicle.Add(jeep);

这样我就可以在Windows窗体应用程序的任何地方访问和修改它,使用像下面这样的按钮点击:

MessageBox.Show(Vehicle[0].name)

我错过了一些东西。我如何使列表车辆公开?

如何使类列表可公开访问

考虑到您所展示的内容,单例模式现在对您来说似乎有点太多了。如果您不同意,请告诉我们,我们会为您指出正确的方向,现在,请尝试这样做:

public class AcessStuff
{
  public static List<Vehicle> CarList = new List<Vehicle>();
}

你可以像这样访问它:

private void SomeFunction()
{
  MessageBox.Show(AcessStuff.CarList[0].Name)
}

如果您希望列表是readonly,那么您只需要提供getter

public class Vehicles
{
    private static readonly List<Vehicle> _vehicles = new List<Vehicle>();
    public static List<Vehicle> Instance { get { return _vehicles; } }
}

实际上,我将参考这个链接的单例

这里有一个版本:

public sealed class Singleton
 {
     private static readonly Singleton instance = new Singleton();
     // Explicit static constructor to tell C# compiler
     // not to mark type as beforefieldinit
     static Singleton()
     {
     }
     private Singleton()
     {
     }
     public static Singleton Instance
     {
         get
         {
             return instance;
         }
     }
 }

许多程序员认为使用静态是有害的,通常这是一个糟糕设计的标志。你真的需要一个单例来访问你的类和对象吗?

有两种方法可以做到这一点。

一种方法是在项目中创建一个Data.cs文件,在此放置所有全局应用程序数据。例如:

Data.cs

public static class ApplicationData
{
    #region Properties
    public static List<Vehicle> CarList
    {
        get
        {
            return ApplicationData._carList;
        }
    }
    private static List<Vehicle> _carList = new List<Vehicle>();
    #endregion
}

第二步是在窗口类中创建变量carList。例如:

public class MyWindow : Window
{
    #region Properties
    public List<Vehicle> CarList
    {
        get
        {
            return this._carList;
        }
    }
    private List<Vehicle> _carList = new List<Vehicle>();
    #endregion
    /* window stuff */
}

使用静态对象

 public static List<string> vehicles =new  List<string> ();
静态类和类成员用于创建无需创建类实例即可访问的数据和函数。静态类成员可以用来分离独立于任何对象标识的数据和行为:无论对象发生了什么,数据和函数都不会改变。静态类可以在类中没有依赖于对象标识的数据或行为时使用。