我在这里需要一点图案方向。C# 新手。
我正在使用包装 Web 服务的第三方开发工具包。我处理了两个特定的类,虽然相对相似,但它们位于开发工具包中的两个不同的命名空间中,并且没有通用的基类。但是,我想针对他们俩的通用接口进行编程。我随意地将一个基本上包装了包装器的实现拼凑在一起,但由于不断的类型转换,我觉得它不是最有效的方法。
我一直在挖掘关于适配器、接口、扩展方法等的文章,但我的时间不多了,所以如果我能朝一个方向推进,我将不胜感激。
using ThirdParty.TypeA.Employee;
using ThirdParty.TypeB.Employee;
public class Employee
{
private object genericEmployee;
private EmployeeType empType;
public enum EmployeeType
{
TypeA = 0;
TypeB = 1;
}
public Employee(Object employee, EmployeeType type)
{
genericEmployee = employee;
empType = type;
}
public String Name
{
if (empType == EmployeeType.TypeA)
return (ThirdParty.TypeA.Employee)genericEmployee.Name;
else
return (ThirdParty.TypeB.Employee)genericEmployee.Name;
}
public String Age
{
if (empType == EmployeeType.TypeA)
return (ThirdParty.TypeA.Employee)genericEmployee.Age;
else
return (ThirdParty.TypeB.Employee)genericEmployee.Age;
}
}
修订版 2:
class EmployeeTypeAAdapter : TypeA, IEmployeeAdapter
{
TypeA _employee;
public EmployeeTypeAAdapter(TypeA employee)
{
_employee = employee
}
public String Name
{
get { return _employee.Name; }
set { _employee.Name = value; }
}
public String Balance
{
get
{
if (_employee.Balance != null)
{
decimal c = _employee.Balance.Amount;
return String.Format("{0:C}", c);
}
else
{
return "";
}
}
}
//...
}
class EmployeeTypeBAdapter : TypeB, IEmployeeAdapter
{
TypeB _employee;
public EmployeeTypeAAdapter(TypeB employee)
{
_employee = employee
}
public String Name
{
get { return _employee.Name; }
set { _employee.Name = value; }
}
public String Balance
{
get
{
if (_employee.Balance != null)
{
decimal c = _employee.Balance.Amount;
return String.Format("{0:C}", c);
}
else
{
return "";
}
}
}
//....
}