How can you use optional parameters in C#?

前端 未结 23 2567
逝去的感伤
逝去的感伤 2020-11-22 17:02

Note: This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).

We\'re building a web API tha

23条回答
  •  一向
    一向 (楼主)
    2020-11-22 17:42

    optional parameters are for methods. if you need optional arguments for a class and you are:

    • using c# 4.0: use optional arguments in the constructor of the class, a solution i prefer, since it's closer to what is done with methods, so easier to remember. here's an example:

      class myClass
      {
          public myClass(int myInt = 1, string myString =
                                 "wow, this is cool: i can have a default string")
          {
              // do something here if needed
          }
      }
      
    • using c# versions previous to c#4.0: you should use constructor chaining (using the :this keyword), where simpler constructors lead to a "master constructor". example:

      class myClass
      {
          public myClass()
          {
          // this is the default constructor
          }
      
          public myClass(int myInt)
              : this(myInt, "whatever")
          {
              // do something here if needed
          }
          public myClass(string myString)
              : this(0, myString)
          {
              // do something here if needed
          }
          public myClass(int myInt, string myString)
          {
              // do something here if needed - this is the master constructor
          }
      }
      

提交回复
热议问题