gpt4 book ai didi

c# - 有条件地限制属性(property)访问

转载 作者:行者123 更新时间:2023-12-02 05:56:16 25 4
gpt4 key购买 nike

是否有更好的方法来限制对职业和雇主属性的访问?

此类只是为了收集一个人(潜在客户)的就业信息而设计的。就业状态可以是就业、自雇、失业、退休等...

我只希望此类用户能够在该人确实受雇的情况下设置雇主和职业。

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;
}
}

最佳答案

如果未设置值,仅返回 null 有什么问题吗?这是相当常见的做法。如果Employer不存在,则其值为空。为什么它是 null 可能不相关。此外,还强制在类本身的 ctor 内设置就业状态。

关于c# - 有条件地限制属性(property)访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4409967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com