首页 新闻 会员 周边 捐助

关于构造函数中使用this的问题

0
悬赏园豆:20 [已解决问题] 解决于 2012-04-12 19:40

第一种方式:

class Motorcycle         {             public int driverIntensity;             public string driverName;

            public void SetDriverName(string name)             { this.driverName = name; }

            public void PopAWheely()             {                 for (int i = 0; i <= driverIntensity; i++)                 {                     Console.WriteLine("Yeeeeeee Haaaaaeewww!");                 }             }             public Motorcycle(int intensity)             {                 if(intensity>10)                 {                     intensity = 10;                 }                 driverIntensity = intensity;             }             public Motorcycle(int intensity,string name):this(intensity)             {                 driverName = name;             }         }

 

第二种方式:

class Motorcycle     {         public int driverIntensity;         public string driverName;

         public void SetDriverName(string name)          { this.driverName = name; }

         public void PopAWheely()          {              for (int i = 0; i <= driverIntensity; i++)              {                  Console.WriteLine("Yeeeeeee Haaaaaeewww!");              }          }

         public Motorcycle(int intensity)              : this(intensity, "")          {              Console.WriteLine("In ctor taking an int");          }

                 public Motorcycle(int intensity, string name)          {              Console.WriteLine("In master ctor ");              if (intensity > 10)              {                  intensity = 10;              }              driverIntensity = intensity;              driverName = name;          }              }

这两种方式哪个更好些?还是说只是习惯性的问题?

C#
微澜的主页 微澜 | 初学一级 | 园豆:-1
提问于:2012-04-05 14:59
< >
分享
最佳答案
0

第一種好。:this中的方法,應該 最好是 小於等於 前面方法中的參數。

收获园豆:10
無限遐想 | 老鸟四级 |园豆:3740 | 2012-04-05 15:11
其他回答(1)
0

Java转过来的么……完全是Java的写法。

class Motorcycle
{
public int DriverIntensity { get; private set; }
public string DriverName { get; set; }

public Motorcycle(int intensity) : this(intensity, "") { }

public Motorcycle(int intensity, string name)
{
this.DriverIntensity = intensity;
this.DriverName = name;
}
}

你把driverIntensity做成公开字段的话,那你的 if (intensity > 10) 还有什么用啊,随便改啊。

收获园豆:10
水牛刀刀 | 园豆:6350 (大侠五级) | 2012-04-05 15:42

不是java转过来的,第二种方法是我从C#与.net4高级程序设计中转过来的,第一种方法是我根据这个类再结合C#图解教程中介绍的怎么用this串联构造函数中的思想改编的,就是想问问哪种编程方式比较好~话说又是你帮我解决问题,哈哈,本人菜鸟一个..

支持(0) 反对(0) 微澜 | 园豆:-1 (初学一级) | 2012-04-05 15:47
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册