自动属性和构造函数的意外 C# 行为

发布于 2024-09-24 14:14:19 字数 2999 浏览 2 评论 0原文

我花了一些调试才弄清楚这一点(或者我是这么认为的)。我会将代码交给您,看看您能想到什么。有一个简单的 Contact 类,其中包含:

  1. 一些自动属性,
  2. 一个参数化构造函数,它始终递增 Contact.ID 属性,并根据它获得的参数设置其他属性
  3. 无参数构造函数总是使用默认值调用参数化构造函数。

首先看代码;其输出和问题遵循以下代码:

 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 = "[email protected]"
         },

         //Contact 2
         new Contact {
            Name = "contactName2",
            Age = 41,
            Email = "[email protected]"
         },

         //Contact 3
         new Contact("contactName3",
            42,
            "[email protected]"),
      };

      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, "[email protected]");  
    }

    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 protected]]  
[Contact: Id=0, Name=contactName2, Age=41, [email protected]]  
[Contact: Id=3, Name=contactName3, Age=42, [email protected]] 

问题:

为什么第二个和第三个联系人中的 Contact.ID == 0 而分别是 1 和 2,尽管参数化构造函数总是被调用并且总是增加 ID 属性?

It took me some debugging to figure this out (or so do I think). I will let the code loose on you and see what you come up with. There is a simple Contact class with:

  1. Some auto-properties,
  2. A parameterized constructor which always increments the Contact.ID property and sets other properties according to the arguments it gets
  3. A parameterless constructor which always calls the parameterized constructor with default values.

First see the code; its output and the question follows the code:

 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 = "[email protected]"
         },

         //Contact 2
         new Contact {
            Name = "contactName2",
            Age = 41,
            Email = "[email protected]"
         },

         //Contact 3
         new Contact("contactName3",
            42,
            "[email protected]"),
      };

      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, "[email protected]");  
    }

    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);
    }
}

Output:

[Contact: Id=0, Name=, Age=, Email=]  
[Contact: Id=0, Name=contactName1, Age=40, [email protected]]  
[Contact: Id=0, Name=contactName2, Age=41, [email protected]]  
[Contact: Id=3, Name=contactName3, Age=42, [email protected]] 

Question:

Why is the Contact.ID == 0 in the second and third contacts rather being 1 and 2 respectively, despite the parameterized constructor being always called and always increment the ID property?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

短叹 2024-10-01 14:14:19

您的默认构造函数不会执行您认为的操作:

public Contact()
{
    new Contact("ANONYMOUS", null, "[email protected]");
}

这将构造一个新的Contact,然后丢弃它,当前实例将获得所有默认值。这是您需要的语法:

public Contact()
  : this("ANONYMOUS", null, "[email protected]")
{
}

Your default constructor doesn't do what you think it does:

public Contact()
{
    new Contact("ANONYMOUS", null, "[email protected]");
}

This will construct a new Contact and then discard it, the current instance will get all default values. Here is the syntax you're after:

public Contact()
  : this("ANONYMOUS", null, "[email protected]")
{
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文