【问题标题】:What ": this" means in C#? [duplicate]“:this”在C#中是什么意思? [复制]
【发布时间】:2015-05-01 22:19:56
【问题描述】:

我正在查看一些代码,我看到了:

public class AccountController : Controller
{
   public AccountController()   
          : this(new xxxxxx...

我理解是AccountController的构造函数,但是是":this"的意思吗?

谢谢, 扎莱克

【问题讨论】:

    标签: c# model-view-controller controller


    【解决方案1】:

    :this在构造函数之后会调用构造函数的另一个重载。

    考虑一下:

    public class Offer {
        public string offerTitle { get; set; }
        public string offerDescription { get; set; }
        public string offerLocation { get; set; }
    
        public Offer():this("title") {
    
        }
    
        public Offer(string offerTitle) {
            this.offerTitle = offerTitle;
        }
    }
    

    如果调用者调用new Offer(),那么,它会在内部调用另一个构造函数,将offerTitle 设置为“title”。

    【讨论】:

      【解决方案2】:

      它确保调用同一个类中的重载构造函数,例如:

      class MyClass
      {
          public MyClass(object obj) : this()
          {
              Console.WriteLine("world");
          }
      
          public MyClass()
          {
              Console.WriteLine("Hello");
          }
      }
      

      使用参数调用构造函数时的输出:

      你好

      世界

      【讨论】:

      • 实际输出将是“Helloworld”
      • Console.WriteLine 附加一个行终止符,所以不 - 它不会。
      • 糟糕,甚至是“Hello world”。没关系
      【解决方案3】:

      :this表示会调用父类的主类构造函数(本例为Controller)

      【讨论】:

      • 这个答案是错误的。
      【解决方案4】:

      this 关键字允许您从同一类中的另一个构造函数调用一个构造函数。假设您的类中有两个构造函数,一个带参数,一个不带参数。可以在不带参数的构造函数上使用this关键字,将默认值传递给带参数的构造函数,如下所示:

      public class AccountController : Controller
      {
         public AccountController() : this(0, "")   
         {
             // some code
         }
      
         public AccountController(int x, string y)   
         {
             // some code
         }
      }
      

      还有一个base 关键字,您可以使用它来调用基类中的构造函数。下面代码中的构造函数会调用Controller类的构造函数。

      public class AccountController : Controller
      {
         public AccountController() : base()   
         {
             // some code
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-05-06
        • 2017-07-09
        • 1970-01-01
        • 2014-05-20
        • 2011-05-10
        • 2019-09-12
        • 2011-09-10
        • 1970-01-01
        • 2015-06-25
        相关资源
        最近更新 更多