如何在没有 SQL 的情况下使用 Class 作为 C# 中 DataGridView 的数据库?

How to use a Class as a database for DataGridView in C# without an SQL?

我必须使用 class 作为 winforms 项目的数据库,用于学校项目,但我们还没有学习 mySQL。我如何在没有 mySQL 的情况下使用 class 作为数据库?

谨防不喜欢,我想建议使用 Singleton pattern 创建一个 class,它将一些 List<T> 存储为“数据库 table”。也可能有几个 Lists,每个代表不同的“数据库 tables”(public List<T> Customerspublic List<T> Sales 等)。

public sealed class RuntimeDatabase
{
    private List<Person> persons = new List<Person>();

    // List used as database table
    public List<Person> Persons
    {
        get => persons;
        private set => persons = value;
    }

    // Singleton
    private static readonly RuntimeDatabase instance = new RuntimeDatabase();

    public static RuntimeDatabase Instance => instance;

    private RuntimeDatabase() { }
}

您可以在其他地方使用它:

public partial class MainWindow : Window
{
    private readonly RuntimeDatabase DB = RuntimeDatabase.Instance;

    private void GetPersons()
    { 
        dataGrid.ItemsSource = DB.Persons;
    }

    private void AddPerson()
    {   
        Person p = new Person();
        p.Name = "John Wick";
 
        DB.Persons.Add(p);
    }

    private void RemovePerson()
    {   
        Person p = new Person();
        p.Name = "John Wick";
 
        DB.Persons.Remove(p);
    }
}

或在 RuntimeDatabase class 中创建自定义方法包装器以模仿 InsertUpdateDeleteTruncateSelect等动作。

素描:

public sealed class RuntimeDatabase
{  
    //...

    public List<Person> Select(Func<Person, bool> func)
    {
        return persons.Where(func).ToList();
    }

    public void Insert(Person person)
    {
        persons.Add(person);
    }

    public void Update(Person person)
    {
        persons = persons.Select(x => 
        { 
            if (x.ID == person.ID) // It's preferred to have an ID property to unique each Person (some kind of Primary Key)
            {
                x.SomeProperty = person.SomeProperty;
            }

            return x;
        }).ToList();
    }

    public int Delete(Predicate<Person> predicate)
    {
        return persons.RemoveAll(predicate); // Count of removed elements
    }

    public void Truncate()
    {
        persons.Clear();
    }
}

当然你可以创建一个方法在应用程序退出之前将它保存到某个文件并在应用程序启动时加载回来。

Person 示例中使用的是简单模型 class:

public class Person 
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string SomeProperty { get; set; }
}

随意向我扔泥。