C#可以使用哪些数组初始化语法?
当前回答
无LINQ重复:
float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);
其他回答
带有表达式的平凡解决方案。注意,使用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
这些是简单数组的当前声明和初始化方法。
string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
string[] array = new[] { "A", "B" }; // created populated array of length 2
注意,还有其他获取数组的技术,例如IEnumerable<T>上的Linq ToArray()扩展。
还要注意,在上面的声明中,前两个可以用var(C#3+)替换左边的字符串[],因为右边的信息足以推断正确的类型。第三行必须按照显示的方式编写,因为仅使用数组初始化语法不足以满足编译器的要求。第四个也可以使用推理。因此,如果你关注整个简短的事情,上面的内容可以写成
var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
var array = new[] { "A", "B" }; // created populated array of length 2
无LINQ重复:
float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);
只是一张纸条
以下阵列:
string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };
将编译为:
string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };
创建和初始化对象数组的另一种方法。这与上面@Amol发布的示例类似,只是这一个使用了构造函数。一点点多态性洒了进来,我无法抗拒。
IUser[] userArray = new IUser[]
{
new DummyUser("abc@cde.edu", "Gibberish"),
new SmartyUser("pga@lna.it", "Italian", "Engineer")
};
上下文类:
interface IUser
{
string EMail { get; } // immutable, so get only an no set
string Language { get; }
}
public class DummyUser : IUser
{
public DummyUser(string email, string language)
{
m_email = email;
m_language = language;
}
private string m_email;
public string EMail
{
get { return m_email; }
}
private string m_language;
public string Language
{
get { return m_language; }
}
}
public class SmartyUser : IUser
{
public SmartyUser(string email, string language, string occupation)
{
m_email = email;
m_language = language;
m_occupation = occupation;
}
private string m_email;
public string EMail
{
get { return m_email; }
}
private string m_language;
public string Language
{
get { return m_language; }
}
private string m_occupation;
}