【问题标题】:definition of static arrays静态数组的定义
【发布时间】:2011-06-03 10:49:03
【问题描述】:

我一直在寻找一个不错的静态数组定义。我试过使用 msdn 和 c# 源,但似乎找不到定义。它给出了例子,但没有定义......

请问有人知道静态数组的任何链接或定义和特征吗?

【问题讨论】:

标签: c# arrays static definition characteristics


【解决方案1】:

您可能是指固定大小的数组吗?

unsafe struct Foo
{
    fixed int Values[8];
}

如果是这样,您将通过使用固定大小的数组作为查询获得更多搜索结果:)

【讨论】:

  • 固定大小的数组是我最终理解的静态数组,所以感谢 mattDavey 的输入!它非常受欢迎
  • 有什么方法可以将固定大小的数组添加为类中的成员?
  • @DeanP 不,“固定大小的缓冲区字段只能是结构的成员”。见:docs.microsoft.com/en-us/dotnet/csharp/misc/cs1642
【解决方案2】:

当您谈论“静态数组”时,您实际上是在谈论两个不同的东西。

一个是static 关键字。当应用于变量时,这意味着变量位于class 级别,并且该类型的每个对象都不会获得自己的实例。

array 只是一个用于保存某种类型的多个值的数据结构。

所以,static array 只是一个类级别的数组,可以保存多个某种数据类型。

例如:

在您的TravelRoute 课程中,您可能在一条路线中有一定数量的可能目的地。这些可以这样定义:

class TravelRoute {
    public static Destination[] possibleDestinations = 
           new Destination[]{
                 new Destination("New York"),
                 new Destination("Minneapolis"),
                 new Destination("NParis")
           };
}

这将在TravelRoute 上定义可能的目的地。然后你可以像这样访问数组:

Destination one = TravelRoute.possibleDestinations[0];

【讨论】:

    【解决方案3】:

    静态数组本身并没有什么特别之处(据我所知),这可能就是为什么你很难找到关于它们的好文章的原因。如果我错了,请纠正我,但我想知道它是否是您最感兴趣的“静态”部分?基本上,静态意味着成员存在于类级别而不是实例级别,因此静态数组将是属于类(而不是类的实例)的数组。

    例子:

    public class Foo
    {
       public static int[] Numbers {get; set;}
    }
    
    public class Bar
    {
       public int[] Numbers {get;set;}
    }
    
    public class Program
    {
         public void Main()
         {
    // NOTE: Foo itself has this array
              Foo.Numbers = new int[]{1,2,3};
    
    // NOTE: it's this particular instance of a Bar that has this array
               Bar bar = new Bar();
               bar.Numbers = new int[]{1,2,3};
    
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多