C# 是否有一种方法可以创建静态只读数组,但这些值是在构建时计算的

C# 是否有一种方法可以创建静态只读数组,但这些值是在构建时计算的,c#,.net,arrays,static,C#,.net,Arrays,Static,有没有一种方法可以创建一个具有只读值的静态数组,但使用一些逻辑来创建它?让我试着解释一下: 我知道我能做到: public static readonly int[] myArray = { 1, 2, 3 }; 但是,有没有可能采取如下措施: public static readonly int[] myArray2 = { for (int i = 0; i < 256; i++) { float[i] = i; } }; 公共静态只读in

有没有一种方法可以创建一个具有只读值的静态数组,但使用一些逻辑来创建它?让我试着解释一下:

我知道我能做到:

public static readonly int[] myArray = { 1, 2, 3 };
但是,有没有可能采取如下措施:

public static readonly int[] myArray2 = 
{
    for (int i = 0; i < 256; i++)
    {
        float[i] = i;
    }
};
公共静态只读int[]myArray2=
{
对于(int i=0;i<256;i++)
{
浮点数[i]=i;
}
};
编辑: 我的问题的一个很好的解决方案:静态构造函数!:你能做的是:

public class YourClass
{
    public static readonly int[] myArray2 = null;

    static YourClass()
    {
        myArray2 = new int[256];
        for (int i = 0; i < 256; i++)
        {
            myArray2 [i] = i;
        }        
    }
}
是的,试试看:

public static readonly IEnumerable<int> myArray = CreateValues();
public static IEnumerable<int> CreateValues()
{
  return new int[] { 1, 2, 3 };
}
公共静态只读IEnumerable myArray=CreateValues(); 公共静态IEnumerable CreateValues() { 返回新的int[]{1,2,3}; } 现在我来看看“工作”方式(哦!恐怖!)

公共静态只读int[]myArray2=(
(Func)/**/
()=>{var array=newint[]{1,2,3};返回数组;

}/*只读应用于数组实例,而不是其内容。因此,您将无法替换原始数组或修改大小。但是,对数组的单元格没有限制,可以随时修改。

实际上,关键字
readonly
意味着您只能将变量分配/修改到构造函数中

public static readonly int[] values = Enumerable.Range(0, 256).ToArray();
甚至

public static readonly IEnumerable<int> values = Enumerable.Range(0, 256).ToArray();
public static readonly IEnumerable values=Enumerable.Range(0,256).ToArray();

请参阅。

这在技术上是在运行时,而不是在构建时(根据要求)。但是,这是我的做法,因为C#缺少宏系统。我认为这是一种过分的做法。如果可以内联或在ctor中调整数组的大小,它的内容可以随时设置/更改。我只想在静态属性中创建一次数组,如果在运行时没有问题,我表达得很糟糕。我认为这个解决方案(静态类或单例)解决了我的问题。谢谢。C#可以发现委托的类型(这就是Func)。它还可以发现lambda的类型(这可能就是您的意思)。它不能做的是仅根据
return
语句自动发现lambda的类型。也就是说,与
Enumerable.Range(0,256).ToArray()相比,这是一个丑陋的问题
是的,当然。我明白了。我只是说这会给维护人员带来噩梦。@John我认为它与Javascript符号相比更有趣。JS符号非常常见(例如在jQuery中)。这就像是说:在这里你可以这样做,在这里你不能。我第一次(几个月前)浪费了一个小时我试着从JS转换它。谢谢你记得我。有什么建议可以解决这个问题吗?不过,我不确定你的目标是什么。你想在数组被填充后密封它吗(即,没有其他人可以修改任何单元格)?建议的解决方案都不能做到这一点,那么你为什么要求“只读”呢字段?是的,静态构造函数是我在帖子中向您展示的;-)问题不太清楚。英语不是我的语言,但我知道您将创建一个“具有只读值的数组”,因此它的单元格不能修改,数组实例本身不能修改。
// ILLEGAL IN C#!!! DANGER, WILL ROBINSON!
public static readonly int[] myArray2 = (() => {
    var array = new int[] { 1, 2, 3 };
    return array;
})();
public static readonly int[] myArray2 = (
    (Func<int[]>) /* <-- The cast to Func<int[]> delegate */ 
    ( 
    /* Start Declaration --> */ 
        () => { var array = new int[] { 1, 2, 3 }; return array;
    } /* <-- End Declaration */ 
    )
    ) 
    (); /* <-- Here we call it! */ 
public static readonly int[] Array = CreateArray();

private static int[] CreateArray()
{
    return new[] { 1, 2, 3, 4, 5 };
}
public static readonly int[] values = Enumerable.Range(0, 256).ToArray();
public static readonly IEnumerable<int> values = Enumerable.Range(0, 256).ToArray();