【发布时间】:2010-12-10 14:47:44
【问题描述】:
有没有更好的方法来限制对 Occupation 和 Employer 属性的访问?
这个类只是为了收集一个人(潜在客户)的就业信息而设计的。 EmployedStatus 可以是 Employed、SelfEmployed、Unemployed、Retired 等...
我只希望这个类的用户能够设置 Employer 和 Occupation(如果该人确实被雇用)。
public class EmploymentInformation
{
private const string _EmploymentStatusNotEmployedMessage = "Employment status is not set to employed";
private string _occupation;
private Company _employer;
/// <summary>The person's employment status<example>Employed</example></summary>
public EmploymentStatus EmploymentStatus { get; set; }
/// <summary>The person's occupation<example>Web Developer</example></summary>
public string Occupation
{
get
{
if (IsEmployed)
{
return _occupation;
}
throw new ApplicationException(_EmploymentStatusNotEmployedMessage);
}
set
{
if (IsEmployed)
{
_occupation = value;
}
throw new ApplicationException(_EmploymentStatusNotEmployedMessage);
}
}
/// <summary>The person's employer</summary>
public Company Employer
{
get
{
if (IsEmployed)
{
return _employer;
}
throw new ApplicationException(_EmploymentStatusNotEmployedMessage);
}
set
{
if (IsEmployed)
{
_employer = value;
}
throw new ApplicationException(_EmploymentStatusNotEmployedMessage);
}
}
private bool IsEmployed
{
get
{
return EmploymentStatus == EmploymentStatus.Employed
|| EmploymentStatus == EmploymentStatus.SelfEmployed;
}
}
/// <summary>
/// Constructor for EmploymentInformation
/// </summary>
/// <param name="employmentStatus">The person's employment status</param>
public EmploymentInformation(EmploymentStatus employmentStatus)
{
EmploymentStatus = employmentStatus;
}
}
【问题讨论】:
-
为什么
Occupation和Employer不能只返回null?为什么在设置属性之一时检查IsEmployed?这不会阻止失业者就业吗?
标签: c# oop design-patterns