【问题标题】:Using a class in a static arrayed list C#在静态数组列表 C# 中使用类
【发布时间】:2015-07-18 13:57:59
【问题描述】:

这是我想要完成的 - 我希望这个类可以全局访问,我需要它的 6 个实例。所以基本上它应该是类似于 List[6] 的东西,它将在公共静态类中初始化......

class HH
{
    public string hand { get; set; }
    public string user { get; set; }
    public int z { get; set; }
    public int bb { get; set; }
    public int eff { get; set; }
    public int pos { get; set; }
    public string pre { get; set; }
    public string f { get; set; }
    public string t { get; set; }
    public string r { get; set; }

}


public static class tx
{
public static List<HH>[] HH = new List<HH>[6];
}

现在观察。这是错误的 - 但也许你明白我试图完成的事情。有人可以告诉我如何实现这一点,以便在我的代码中我可以访问类的元素并对其进行读写吗?

【问题讨论】:

  • 你能写更多关于你的情况吗? (你想用它做什么以及为什么),这似乎仍然太少信息(至少对我来说)。
  • 是的,你为什么需要这样做?

标签: list class generics static


【解决方案1】:

"公共静态列表[] HH = 新列表[6];" 我认为这还不够。您只初始化了数组,但留下了 HH 对象。在该代码之后,您可以编写一个循环来实例化每个 HH 对象。 我希望这会有所帮助。但如果没有,如果你能提供更多细节可能会很棒。 :)

【讨论】:

    【解决方案2】:

    你可以这样做:

    public static class TX
    {    
       public static List<HH> _HH { get; private set; } 
    
       static TX()
       {
           _HH = new List<HH>()
           {
              new HH(), new HH(), new HH(),
              new HH(), new HH(), new HH()
           };
       }
    
        internal class HH
        {
            public string hand { get; set; }
            public string user { get; set; }
            public int z { get; set; }
            public int bb { get; set; }
            public int eff { get; set; }
            public int pos { get; set; }
            public string pre { get; set; }
            public string f { get; set; }
            public string t { get; set; }
            public string r { get; set; }    
        }    
    }
    

    并像这样使用它:

    var hand = TX._HH[0].hand;
    

    【讨论】:

    • 非常感谢,这就是我想要的。我必须将公共静态类更改为仅类,否则会出现访问不兼容问题,现在如果我要设置它,例如我只是做 TX._HH[0].user = "xxx"。干杯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2015-02-01
    • 2019-03-25
    • 1970-01-01
    相关资源
    最近更新 更多