我正在使用包装Web服务的第三方开发工具包.我处理的两个特定类虽然相对类似,但是在devkit中有两个不同的命名空间,并且没有共同的基类.但是,我想为它们编写一个针对它们的通用接口.我随意地将一个基本上包装了包装器的实现组合在一起,但我觉得由于不断的类型转换,我认为它不是最有效的方法.
我一直在挖掘关于适配器,接口,扩展方法等的文章.但是我的运行时间很少,所以如果我能够在一个方向上推动,那将非常感激.
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 ""; } } } //....}解决方法 试试这种方法:
public interface IEmployeeAdapter{ string Age { get; set; } string name { get; set; }}class EmployeeTypeAAdapter : TypeA,IEmployeeAdapter{ public EmployeeTypeAAdapter(TypeA employee) { }}class EmployeeTypeBAdapter : TypeB,IEmployeeAdapter{ public EmployeeTypeBAdapter(TypeB employee) { }}public static class EmployeeAdapterFactory{ public static IEmployeeAdapter CreateAdapter(object employee,EmployeeType type) { switch (type) { case EmployeeType.TypeA: return new EmployeeTypeAAdapter((TypeA)employee); case EmployeeType.TypeB: return new EmployeeTypeBAdapter((TypeB)employee); } } // or without enum public static IEmployeeAdapter CreateAdapter(object employee) { if (employee is TypeA) return new EmployeeTypeAAdapter((TypeA)employee); if (employee is TypeB) return new EmployeeTypeABdapter((TypeB)employee); } // or better introduce sort of type map}
另一个专有名称是EmployeeProxy,如您所愿.
总结以上是内存溢出为你收集整理的c# – 我无法控制的两个第三方类的通用接口.外部多态性?全部内容,希望文章能够帮你解决c# – 我无法控制的两个第三方类的通用接口.外部多态性?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)