C#可以使用哪些数组初始化语法?
当前回答
Enumerable.Repeat(String.Empty, count).ToArray()
将创建重复“count”次的空字符串数组。若您希望使用相同但特殊的默认元素值初始化数组。注意引用类型,所有元素都将引用同一对象。
其他回答
创建自定义类数组的示例
下面是类定义。
public class DummyUser
{
public string email { get; set; }
public string language { get; set; }
}
这是初始化数组的方法:
private DummyUser[] arrDummyUser = new DummyUser[]
{
new DummyUser{
email = "abc.xyz@email.com",
language = "English"
},
new DummyUser{
email = "def@email.com",
language = "Spanish"
}
};
int[] array = new int[4];
array[0] = 10;
array[1] = 20;
array[2] = 30;
or
string[] week = new string[] {"Sunday","Monday","Tuesday"};
or
string[] array = { "Sunday" , "Monday" };
并且在多维阵列中
Dim i, j As Integer
Dim strArr(1, 2) As String
strArr(0, 0) = "First (0,0)"
strArr(0, 1) = "Second (0,1)"
strArr(1, 0) = "Third (1,0)"
strArr(1, 1) = "Fourth (1,1)"
For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };
创建和初始化对象数组的另一种方法。这与上面@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;
}
要初始化空数组,在dotnet 5.0中应该是array.empty<T>()
对于字符串
var items = Array.Empty<string>();
对于编号
var items = Array.Empty<int>();