本质上,我必须使用由其他程序员维护的实现不佳的 Web 服务。它们有两个不是从父类派生的类,但具有相同的属性(呃......)。所以它在我的 Web 服务代理类文件中看起来像这样:
public partial class Product1
{
public int Quantity;
public int Price;
}
public partial class Product2
{
public int Quantity;
public int Price;
}
那么,在不重复代码的情况下从已知属性中获取值的最佳方法是什么?我知道我可能可以使用反射,但这可能会变得很难看。如果有更简单、不那么疯狂的方法(也许在新的 C# 功能中?)请告诉我。
最佳答案
我不确定我完全理解你的情况,但也许是这样的?
使用 getQuantity
和 getPrice
方法定义 IProduct
接口(interface),并在两个类中实现它:
public partial class Product1 : IProduct
{
public int Quantity;
public int Price;
public int getQuantity() { return Quantity; }
public int getPrice() { return Price; }
}
另一个也类似;然后将它们都用作IProduct
。
关于c# - 从不使用继承的两个类(具有相同的属性名称)获取属性值的优雅解决方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2787231/