c# - 从不使用继承的两个类(具有相同的属性名称)获取属性值的优雅解决方案是什么?

标签 c# web-services reflection class properties

本质上,我必须使用由其他程序员维护的实现不佳的 Web 服务。它们有两个不是从父类派生的类,但具有相同的属性(呃......)。所以它在我的 Web 服务代理类文件中看起来像这样:

public partial class Product1
{
    public int Quantity;
    public int Price;
}

public partial class Product2
{
    public int Quantity;
    public int Price;
}

那么,在不重复代码的情况下从已知属性中获取值的最佳方法是什么?我知道我可能可以使用反射,但这可能会变得很难看。如果有更简单、不那么疯狂的方法(也许在新的 C# 功能中?)请告诉我。

最佳答案

我不确定我完全理解你的情况,但也许是这样的? 使用 getQuantitygetPrice 方法定义 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/

相关文章:

Java 使用泛型创建新类

c# - 从串口读取值

c# - 如何递归迭代实体的属性

c# - 是否有必要释放从 C# 接收到的 C++ 字符串的内存?

java - 在 spring restful webservice 中返回 JsonObject

c# - 动态创建属性

c# - 如何验证 ILogger<T>.Log 扩展方法是否已使用 Moq 调用?

python - 如何在 Spyne 中设置端口的名称和绑定(bind)?

web-services - spring-ws、CXF、soap(camel组件)调用Web服务有什么区别?

c# - 对于泛型类型,IsConstructedGenericType 是否始终是 IsGenericTypeDefinition 的否定?