C#可以使用哪些数组初始化语法?
当前回答
另一种方法是调用静态函数(用于静态对象)或实例对象的任何函数。这可用于成员初始化。
现在我还没有测试所有这些,所以我将把我测试过的(静态成员和静态函数)
Class x {
private static Option[] options = GetOptionList();
private static Option[] GetOptionList() {
return (someSourceOfData).Select(dataitem => new Option()
{field=dataitem.value,field2=dataitem.othervalue});
}
}
我想知道的是,是否有绕过函数声明的方法。我知道在这个例子中,它可以直接使用,但假设函数稍微复杂一些,不能简化为一个表达式。
我想象如下(但不起作用)
Class x {
private static Option[] options = () => {
Lots of prep stuff here that means we can not just use the next line
return (someSourceOfData).Select(dataitem => new Option()
{field=dataitem.value,field2=dataitem.othervalue});
}
}
基本上是为填充变量的范围声明函数的一种方式。如果有人能教我怎么做,我会很高兴的。
其他回答
非空数组
var data0=新int[3]var data1=新int[3]{1,2,3}var data2=新int[]{1,2,3}var data3=新[]{1,2,3}var data4={1,2,3}不可编译。请改用int[]data5={1,2,3}。
空数组
var data6=新int[0]var data7=新int[]{}vardata8=new[]{}和int[]data9=new[]}不可编译。var data10={}不可编译。请改用int[]data11={}。
作为方法的参数
只有可以指定var关键字的表达式才能作为参数传递。
Foo(新int[2])Foo(新int[2]{1,2})Foo(新int[]{1,2})Foo(新[]{1,2})Foo({1,2})不可编译Foo(新int[0])Foo(新int[]{})Foo({})不可编译
Enumerable.Repeat(String.Empty, count).ToArray()
将创建重复“count”次的空字符串数组。若您希望使用相同但特殊的默认元素值初始化数组。注意引用类型,所有元素都将引用同一对象。
对于C#声明中的多维数组,请赋值。
public class Program
{
static void Main()
{
char[][] charArr = new char[][] { new char[] { 'a', 'b' }, new char[] { 'c', 'd' } };
int[][] intArr = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
}
}
带有表达式的平凡解决方案。注意,使用NewArrayInit,您可以只创建一维数组。
NewArrayExpression expr = Expression.NewArrayInit(typeof(int), new[] { Expression.Constant(2), Expression.Constant(3) });
int[] array = Expression.Lambda<Func<int[]>>(expr).Compile()(); // compile and call callback
无LINQ重复:
float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);
推荐文章
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?
- 更新行,如果它存在,否则插入逻辑实体框架
- 在什么情况下SqlConnection会自动被征召到环境事务范围事务中?
- 用c#解析JSON
- Windows窗体中的标签的换行
- 为什么在c#中使用finally ?
- c++中有最大数组长度限制吗?
- 为什么我不能在c#中有抽象静态方法?
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?