简体   繁体   English

C#构造函数默认参数正确方法

[英]c# constructor default parameters correct way

So I need to understand which way is the correct/best one? 因此,我需要了解哪种方法是正确的/最好的方法?

First way: 第一种方式:

class Customer
{
    string firstName;
    string lastName;

    public Customer(string firstName="non", string lastName="applicable")
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

Second way: 第二种方式:

class Customer
{
    string firstName;
    string lastName;

    public Customer()
    : this("non","applicable")
    { }

    public Customer(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

If I'm creating a method printFullName(), it works in both cases. 如果我正在创建方法printFullName(),则在两种情况下均可以使用。 So which one to chose? 那么选择哪一个呢? The first one seems easier to me. 第一个对我来说似乎更容易。

The second way is better, because it looks like it's your intent to use "non" and "applicable" as the first and last name if they supply no inputs. 第二种方法更好,因为如果您不提供任何输入,则看起来您打算使用“ non”和“ applicable”作为名字和姓氏。

If you have just one constructor with optional arguments, someone could supply a first name and have the last name be "applicable," like "Bob applicable." 如果您只有一个带有可选参数的构造函数,则有人可以提供名字,并且使姓氏为“ applyable”,例如“ Bob apply”。

It's a minor difference because a) it works either way, and b) a consumer can tell what the default parameters are. 这是一个很小的差异,因为a)两种方式都能起作用,并且b)消费者可以知道默认参数是什么。 But the second option seems more in line with your apparent intent. 但是第二种选择似乎更符合您的意图。

To be really particular I'd reconsider those defaults. 确切地说,我会重新考虑这些默认值。 Should someone be able to create a customer without a name? 有人可以创建没有名字的客户吗? If so then perhaps the name should be null. 如果是这样,那么名称应该为空。 Perhaps CustomerName should be a separate class, and Customer has a Name property of of type CustomerName. 也许CustomerName应该是一个单独的类,并且Customer具有类型为CustomerName.Name属性CustomerName. The reason I'm splitting hairs over that is because you want to know if you have a name or not. 我之所以大发雷霆,是因为您想知道自己是否有名字。 Once you supply a fake name that's harder to determine. 一旦提供了虚假名称,就很难确定。 You could send out hundreds of letters to customers named "non applicable." 您可以向名为“不适用”的客户发送数百封信。

In terms of semantics, both ways are correct. 就语义而言,两种方法都是正确的。 Some of the differences between the two are 两者之间的一些区别是

First way: Invoke the constructor as: 第一种方式:将构造函数调用为:

  1. new Customer(firstName="first");
  2. new Customer(lastName="last");
  3. new Customer("first", "last");
  4. new Customer();

Second way: Invoke the constructor as: 第二种方式:将构造函数调用为:

  1. new Customer("first", "last");
  2. new Customer();

So the first way will give you more flexibility in how you can invoke the constructor. 因此,第一种方法将为您提供更多的调用构造函数的灵活性。

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

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