您可以检查它并在运行时抛出异常,如下所示:
if (grade < 2.00 || grade > 6.00)
throw new ArgumentOutOfRangeException("grade");
始终将此类条件放在方法或构造函数的开头。我什至把它们放在自己的#region
(但这是我个人的喜好):
public Student(string firstName, string lastName, double grade)
: base(firstName, lastName)
{
#region Contract
if (grade < 2.00 || grade > 6.00)
throw new ArgumentOutOfRangeException("grade");
#endregion
this.FirstName = firstName;
this.LastName = lastName;
this.Grade = grade;
}
但是,有一种方法可以使用 Code Contracts 获得此类事情的编译时警告。您可以在 MSDN 上下载Code Contracts,还可以在那里找到文档。它仅与非 Express 版本的 Visual Studio 集成,由 Microsoft 编写。它将检查方法调用是否可能遵守您指定的合同。您的代码将变为:
using System.Diagnotistics.Contracts;
public Student(string firstName, string lastName, double grade)
: base(firstName, lastName)
{
#region Contract
Contract.Requires<ArgumentOutOfRangeException>(grade >= 2.00);
Contract.Requires<ArgumentOutOfRangeException>(grade <= 6.00);
#endregion
this.FirstName = firstName;
this.LastName = lastName;
this.Grade = grade;
}