C#中构造函数和属性之间的差异

本文关键字:之间 属性 构造函数 | 更新日期: 2023-09-27 18:26:41

我是编程新手,有人能给我解释一下C#上下文中构造函数和属性之间的区别吗。由于两者都用于初始化类字段,&以及在特定情况下选择哪一个。

C#中构造函数和属性之间的差异

除了所有的技术内容外,一个好的经验法则是对强制性内容使用构造函数参数,对可选内容使用属性。

您可以忽略属性(因此是可选的),但不能忽略构造函数参数(因此是必需的)。

对于其他一切,我建议阅读C#初学者的书或教程;-)

属性只是一个可以在任何时候初始化的类成员。

像这样:

var myClass = new MyClass();
myClass.PropertyA = "foo";
myClass.PropertyB = "bar";

构造函数在创建类时运行,可以执行各种操作。在您的"场景"中,它可能用于初始化成员,以便类在创建时处于有效状态。

像这样:

var myClass = new MyClass("foo", "bar");

Constructor是类中用于创建对象本身的一种特殊类型的方法。您应该使用它来初始化使对象按预期工作所需的一切。

来自MSND构造函数:

创建类或结构时,会调用其构造函数。构造函数与类或结构具有相同的名称,并且通常初始化新对象的数据成员。

属性使类能够存储、设置和公开对象所需的值。您应该创建以帮助类的行为。

来自MSND属性:

属性是提供灵活的读取机制的成员,写入或计算私有字段的值。可以使用属性就好像他们是公共数据成员,但他们实际上是特殊的方法称为访问器。这使得数据可以轻松访问仍然有助于提高方法的安全性和灵活性。

示例:

public class Time
{
   //
   //  { get; set; } Using this, the compiler will create automatically
   //  the body to get and set.
   //
   public int Hour { get; set; } // Propertie that defines hour
   public int Minute { get; set; } // Propertie that defines minute 
   public int Second { get; set; } // Propertie that defines seconds 
   //
   // Default Constructor from the class Time, Initialize
   // each propertie with a default value
   // Default constructors doesn't have any parameter
   //
   public Time()
   {
      Hour = 0;
      Minute = 0;
      Second = 0;
   }

   //
   // Parametrized Constructor from the class Time, Initialize
   // each propertie with given values
   //
   public Time(int hour, int Minute, int second)
   {
      Hour = hour;
      Minute = minute;
      Second = second;
   }
}

属性也应该用于验证传递的值,例如:

public int Hour 
{ 
   //Return the value for hour
   get
   {
     return _hour;
   } 
   set
   {
     //Prevent the user to set the value less than 0
     if(value > 0)
        _hour = 0; 
     else
        throw new Exception("Value shoud be greater than 0");
}
private int _hour;

希望这能帮助你理解!有关C#的更多信息,请参阅面向对象编程(C#和Visual Basic)。