我花了一些调试来解决这个问题(或者我认为是这样)。我会让你的代码松散,看看你提出了什么。有一个简单的Contact
类:
Contact.ID
属性并根据它获得的参数设置其他属性首先看代码;它的输出和问题遵循代码:
using System;
class Program
{
private static void Main(string[] args)
{
Contact[] contacts_array = {
//Contact 0
new Contact(),
//Contact 1
new Contact {
Name = "contactName1",
Age = 40,
Email = "emailaddress1@email.com"
},
//Contact 2
new Contact {
Name = "contactName2",
Age = 41,
Email = "emailaddress2@email.com"
},
//Contact 3
new Contact("contactName3",
42,
"emailaddress3@email.com"),
};
foreach (var contact in contacts_array)
Console.WriteLine(contact);
Console.ReadLine();
}
}
public class Contact
{
public static int totalContacts = 0;
public int Id { get; private set; }
public string Name { get; set; }
public int? Age { get; set; }
public string Email { get; set; }
public Contact()
{
new Contact("ANONYMOUS", null, "ANONYMOUS@unknown.com");
}
public Contact(string name, int? age, string email)
{
Id = Contact.totalContacts++;
Name = name;
Age = age;
Email = email;
}
public override string ToString()
{
return string.Format("[Contact: Id={0}, Name={1}, Age={2}, Email={3}]",
Id, Name, Age, Email);
}
}
输出:
[Contact: Id=0, Name=, Age=, Email=]
[Contact: Id=0, Name=contactName1, Age=40, Email=emailaddress1@email.com]
[Contact: Id=0, Name=contactName2, Age=41, Email=emailaddress2@email.com]
[Contact: Id=3, Name=contactName3, Age=42, Email=emailaddress3@email.com]
问题:
为什么第二个和第三个联系人中的Contact.ID == 0分别为1和2,尽管总是调用参数化构造函数并且总是递增ID属性?
答案 0 :(得分:6)
您的默认构造函数不符合您的预期:
public Contact()
{
new Contact("ANONYMOUS", null, "ANONYMOUS@unknown.com");
}
这将构造一个新的Contact
然后丢弃它,当前实例将获得所有默认值。以下是您要使用的语法:
public Contact()
: this("ANONYMOUS", null, "ANONYMOUS@unknown.com")
{
}