【发布时间】:2013-08-09 00:27:17
【问题描述】:
我是编程新手,谁能解释一下构造函数和属性在 C# 上下文中的区别。 因为两者都用于初始化您的类字段,以及在给定情况下选择哪一个。
【问题讨论】:
-
它们是完全不同的东西。
-
您是否尝试查看有关此的教程和其他线程?
标签: c#
我是编程新手,谁能解释一下构造函数和属性在 C# 上下文中的区别。 因为两者都用于初始化您的类字段,以及在给定情况下选择哪一个。
【问题讨论】:
标签: c#
除了所有技术性的东西,一个好的经验法则是将构造函数参数用于强制事物,将属性用于可选事物。
您可以忽略属性(因此是可选的),但您不能忽略构造函数参数(因此是必需的)。
对于其他一切,我建议阅读 C# 初学者书籍或教程;-)
【讨论】:
属性只是一个可以随时初始化的类成员。
像这样:
var myClass = new MyClass();
myClass.PropertyA = "foo";
myClass.PropertyB = "bar";
构造函数在创建类时运行,可以做各种事情。在您的“场景”中,它可能会用于初始化成员,以便类在创建时处于有效状态。
像这样:
var myClass = new MyClass("foo", "bar");
【讨论】:
构造函数是一种特殊类型的方法,从类中创建对象本身。您应该使用它来初始化使对象按预期工作所需的一切。
来自 MSND Constructor:
当一个类或结构被创建时,它的构造函数被调用。 构造函数与类或结构同名,并且它们 通常初始化新对象的数据成员。
属性使类能够存储、设置和公开对象所需的值。您应该创建以帮助该类的行为。
来自 MSND Property:
属性是提供灵活读取机制的成员, 写入或计算私有字段的值。可以使用属性 好像它们是公共数据成员,但它们实际上是特殊的 称为访问器的方法。这样可以轻松访问数据,并且 仍然有助于提高方法的安全性和灵活性。
例子:
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# 的更多信息,请查看Object-Oriented Programming (C# and Visual Basic)。
【讨论】: