我想知道如何处理 C# 中的依赖属性。我有以下简化类(我正在使用DevExpress XAF):
public class Company
{
public ContactMethods? PreferredContactMethod { get; set; }
// Missing: Collection of Employees...
}
public class Employee
{
private Company company;
public Company Company
{
get
{
return this.company;
}
set
{
company = value;
if (company != null && PreferredContactMethod == null)
{
PreferredContactMethod = company.PreferredContactMethod;
}
}
}
public ContactMethods? PreferredContactMethod { get; set; }
}
在将 Company 分配给 Employee 时,我将 Employee.PreferredContactMethod 设置为 Company 的 PreferredContactMethod(只是为了方便,以后可以更改)。
更新:
我想在初始化新员工时使用 Company.PreferredContactMethod 作为默认值。每个员工都独立于公司存储自己的 ContactMethod。以后对 Company.PreferredContactMethod 的更改不应更新 Employee.PreferredContactMethod。Employee.PreferredContactMethod 为空是完全合法的(例如,如果明确设置为用户)。
非常简单的代码,当然这很好用。但我认为它违反了微软的 Property Design Guidelines:
允许以任何顺序设置属性,即使这会导致临时无效的对象状态。
Company = A, PreferredContactMethod = null
给出另一个结果,而不是PreferredContactMethod = null, Company = A
.
我认为我不能依赖属性设置器的“正确”顺序(例如,如果使用 Automapper/Reflection),您如何处理这种情况?我认为这并不少见。
谢谢!