在一个项目中,我有以下类关系。 Employee
和Client
与Company
有组合关系。所以实现如下。
class Company
{
private Employee _Employee {get;set;} // private fields as composition
private Client _Client {get;set;}
public Company()
{
_Employee = new Employee();
_Client = new Client();
}
public AddEmploees() //Employee objects are controlled by Company
{
//
}
public DeleteEmploees()
{
//
}
public AddClients() //Client objects are controlled by Company
{
//
}
public DeleteClients()
{
//
}
}
class Employee
{
string Name {get;set;}
int ID {get;set;}
string Address {get;set;}
string Department {get;set;}
DateTime DOB {get;set;}
private Employee() // constructor private
{
}
}
class Client
{
string CID {get;set;}
string Name {get;set;}
string Type {get;set;}
DateTime StartDate {get;set;}
string Address {get;set;}
private Client() // constructor private
{
}
}
当我想在 UI 上显示 client
/employee
详细信息时,我的 DataService
应该返回一个 Company
对象而不是返回 Employee/Client
对象,因为关系是组合的。所以我可以在我的 DataService
中使用类似 GetDetails()
的方法,然后从数据库中获取所需的详细信息以分配给 Employee
和客户端
。但现在的问题是,我将无法访问 Company
对象的私有(private)字段(_Employee
、_Client
)来设置属性值如下
public Company GetDetails()
{
Company company = new Company();
string selectStatement = "SELECT...";
// Get data from DB
company.client.name = rdr["name"].value; // This is not possible.
.
.
.
}
虽然我几乎没有解决这个问题的想法,但似乎没有一个适合这种类关系(组合)或违反关注点分离原则。感谢您在这方面的帮助?
最佳答案
看起来你想使用
要实现相互可见性(又名 C++ friend class
),您可以使用
而不是私有(private)可见性。这将允许读/写访问其他对象的属性。 Microsoft 也大量使用它(内部类、内部命名空间,参见例如 http://referencesource.microsoft.com/#PresentationFramework/src/Framework/MS/Internal/Data/CollectionViewGroupInternal.cs )所以它不是被禁止的设计实践,只要它有帮助
关于c# - 数据服务返回对象时的类组成问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23856660/