不可变对象列表使用的设计模式

Design Pattern for List of Immutable Objects usage

假设我有一个类型为 Foo 的对象,初始化后将为 immutable。由于这些对象是不可变的,并且我希望能够访问这些 Foo 对象中的任何一个,因此我将这些对象初始化并存储在一个 static class (FooHandler) 中,其中包含一个 list 所有 Foo 个对象。

但是目前,如果 class 想要访问此对象,我会向他们提供 Foo 对象在 FooHandler 列表中的位置索引,并且有一个getter method 到 return 需要时对象本身。这样做的目的是通过不让两个相同的对象循环(我认为这是一种浪费)来节省内存。

C# 中是否有更好的方法来引用这些对象(如指针或类似的东西)或更好的结构来完全解决这个问题,正如我所想的那样不可变对象的索引太老套且容易出错?

示例代码:

public class Foo {
    public int A { get; private set; }
    public int B { get; private set; }

    public Foo(int a, int b) {
        A = a;
        B = b;
    }
}

public static class FooHandler {
    private static List<Foo> fooList;

    static FooHandler() {
        fooList = new List<Foo>();

        fooList.Add(new Foo(1, 2));
        fooList.Add(new Foo(3, 4));
    }

    // Assume there is error checking
    public static Foo GetFoo(int index) {
        return fooList[index];
    }
}

public class Bar {
    public int FooID { get; private set; }

    public Bar(int fooID) {
        FooID = fooID;
    }

    public void func() {
        Console.WriteLine(FooHandler.GetFoo(FooID).A);
    }
}

注意:我知道这个例子可以被认为是可变的,只是想在没有太多测试的情况下快速输入一些东西。

C# 已经通过引用(大致相当于指针)传递引用类型(由 class 表示)。

您无需执行任何特殊操作即可获得它,它会自动发生。直接返回 Foo 没有浪费。