我对初始化有疑问。当我们使用{}初始化数组时,必须在声明后立即执行以显示编译器要使用的类型。为什么编译器允许Diamond运算符使用2条语句来做到这一点?
Integer[] array = {2,4,5};
//Integer[] array; array = {2,4,5}; - error
List<Integer> list = new ArrayList<>();
//List<Integer> list; list = new ArrayList<>(); - no error
答案 0 :(得分:2)
您也可以对数组进行两行处理,只需在初始化时创建一个新对象(当然也要明确指定类型)。
public class PersonDto
{
private Status status;
public int Id { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public Status LivingStatus
{
get => status;
set
{
status = value;
switch (status)
{
case Status.Homeowner:
IsHomeOwner = true;
IsTenant = false;
IsLivingWithParents = false;
break;
case Status.LivingWithParents:
IsHomeOwner = false;
IsTenant = false;
IsLivingWithParents = true;
break;
case Status.Tenant:
IsHomeOwner = false;
IsTenant = true;
IsLivingWithParents = false;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
public bool IsHomeOwner { get; set; }
public bool IsTenant { get; set; }
public bool IsLivingWithParents { get; set; }
}