在 C# 和 java(具有 GC 的语言)中访问硬编码映射或数组等的最佳方式

Best way to access hard Coded Map or array etc. in C# and java (languages that have GC )

在具有垃圾收集器的编程语言中,访问硬编码变量和对象的最佳方式是什么。我有两个选择:

选项 1:

class Hello {
    void retrieveData() {
       Map map = App.staticMap;
  }
}

public class App {
  public static Map map = new Map<>() {
      "a", "b",
      "b", "d",
   //hundreds of lines      
 }
}

选项 2:

class Hello {

  void retrieveData() {
    //let assume App instance is declared when program is started.
     Map map = App.getInstance().dataMap;
  }
}

public class App {
 private static App instance; 
 Map dataMap = new Map() <> {
   //hundreds of lines
 }

 public static App getInstance() {
    return instance;
 }
}

由于垃圾收集器,我找不到最好的方法。当我调用静态变量时,垃圾收集器可能在调用之前收集了它。我想同样的事情对实例对象有效。 JAVA 和 C# 中哪一个是最好的方法?或者有什么选择吗?

The garbage collector will not collect static references - the rule is that an object becomes eligible for garbage collection when it is not reachable by any live thread. Static objects are always reachable, so they should never be collected: link

For your examples, here are some good practice suggestions:

-Don't access fields directly, it's better to provide a getter. This gives you flexibility to change your implementation later.

-Don't use instance methods to access static fields. This makes for confusing, hard to read code.

-Try to avoid hard-coding data - could you use a properties file to store this map information? Then it would be configurable if you need to change it later.

-Maybe overkill for your needs here, but it might be worth looking into the enum singleton pattern rather than just a static field.

If you really want to hard-code it, my preferred implementation would be

public class App {
  private static Map map = new Map<>() {
      "a", "b",
      "b", "d",
   //hundreds of lines      
 }

 public Map getMap(){
   return map;
 }
}