简体   繁体   English

帮助我了解C#中的这段代码

[英]Help me to understand this code in c#

i can not read this line of code 我看不懂这行代码

public Wine (decimal price, int year) : this (price) { Year = year; }

what :this keyword do in a constructor :this关键字在构造函数中做什么

public class Wine
{
    public decimal Price;
    public int Year;

    public Wine (decimal price) 
    { 
        Price = price; 
    }

    public Wine (decimal price, int year) : this (price) 
    { 
        Year = year; 
    }
}

This is called constructor chaining. 这称为构造函数链接。 Instead of rewriting the code of the one-argument constructor, you simply call it. 无需重写单参数构造函数的代码,只需调用它即可。 C# makes this simple by using this short notation with the colon. C#通过在冒号中使用这种短符号来简化此过程。

this(price) calls another constructor that in this case only takes one parameter of type decimal. this(price)调用另一个构造函数,在这种情况下,该构造函数仅采用一个十进制类型的参数。 As a reference read "Using Constructors" . 作为参考,请阅读“使用构造函数”

I'm not a big fan of this particular example since both constructors do initialization work. 我不是这个特定示例的忠实拥护者,因为两个构造函数都进行初始化工作。

In my opinion it is better to pass default values to one constructor that then does all the work - this way initialization is not spread between different constructors and you have a single spot where everything is initialized - a better way would be: 在我看来,最好将默认值传递给一个构造函数,然后再完成所有工作-这样,初始化不会在不同的构造函数之间分散,并且只有一个地方可以初始化所有内容-一种更好的方法是:

public class Wine
{
   public decimal Price;
   public int Year;
   public Wine (decimal price): this(price, 0)
   public Wine (decimal price, int year) 
   { 
      Price = price;
      Year = year; 
   }
}

它首先使用单个十进制参数price调用构造函数。

It calls another constructor in the same class that has that signature passing the values into it that were supplied to the initial constructor call. 它调用同一类中的另一个构造函数,该构造函数具有将该签名传递给初始构造函数调用的值。 In you example, the Wine class has (at least) two constructors, one that takes a decimal (price) and a int (year), as well as a second one that only takes a decimal (price). 在您的示例中,Wine类具有(至少)两个构造函数,一个构造函数采用decimal (价格)和int (年份),以及第二个构造函数仅采用decimal (价格)。

When you call the one that takes the two parameters, it calls the one that takes only one parameter passing the value of price into the second one. 当您调用带有两个参数的参数时,它将调用仅带有一个参数的参数,将价格值传递给第二个参数。 It then executes the constructor body (setting Year to year). 然后执行构造函数主体(将Year设置为Year)。

This allows you to reuse common logic that should happen no matter which constructor call was made (in this instance setting the price should always happen, but the more specific constructor also sets the Year). 这使您可以重用无论发生哪个构造函数调用都应该发生的常见逻辑(在这种情况下,应始终设置价格,但更具体的构造函数也将设置Year)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM