C# 什么';从两个不使用继承的类(具有相同的属性名)中获取属性值是一个优雅的解决方案吗?

C# 什么';从两个不使用继承的类(具有相同的属性名)中获取属性值是一个优雅的解决方案吗?,c#,web-services,reflection,class,properties,C#,Web Services,Reflection,Class,Properties,从本质上说,我必须使用由其他程序员维护的实现较差的web服务。它们有两个不是从父类派生的类,但具有相同的属性(Ughh…)。在我的web服务代理类文件中,它看起来像这样: public partial class Product1 { public int Quantity; public int Price; } public partial class Product2 { public int Quantity; public int Price; }

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

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

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

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

4.0中的动态关键字?但我不会说它很优雅,但它会工作的。

这里有一些伪代码,很抱歉没有解决它。也许这给了你正确的方向:

列表对象=新列表(); 对象。添加(p1)//您的第一个产品对象 对象。添加(p2)//您的第二个产品对象

    foreach (var o in objects)//go through all projects
    {

        if (o.GetType().Equals(typeof(Product1)) //check which class is behind the object
            ((Product1)o).Price = 2; //convert to fitting class and call your property
        //....
    }

我不确定我是否完全理解你的处境,但也许是这样的? 使用
getQuantity
getPrice
方法定义
IPProduct
接口,并在两个类中实现它:

public partial class Product1 : IProduct
{
  public int Quantity;
  public int Price;
  public int getQuantity() { return Quantity; }
  public int getPrice() { return Price; }
}

另一个也一样;然后将它们都用作
IProduct

如果类是从web代理生成的,则可以实现实现公共接口的部分类

从代理生成:

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

public partial class Product2 {
    public int Quantity;
    public int Price;
}
手写:

public interface IProduct {
    int Quantity { get; }
    int Price { get; }
}

public partial class Product1:IProduct {
    int IProduct.Quantity { get { return Quantity; } }
    int IProduct.Price { get { return Price; } }
}

public partial class Product2:IProduct {
    int IProduct.Quantity { get { return Quantity; } }
    int IProduct.Price { get { return Price; } }
}

现在,您的两个类都实现了
ipproduct
,并且可以以相同的方式进行传递。

您可以更改这些类吗?您可以将代码添加到
Product
类吗?我可能可以,因为我正在做的是从web服务创建一个代理类并使用它,但这可能很难维护,比如如果他们更新Web服务,我重新创建代理类,我必须记住我所做的更改,并且每次都进行更改。虽然它可能会起作用,但它不应该被用作糟糕设计的支柱,如果这是唯一的解决方案,那么我会说它比反射好一点。是的,我完全同意你的观点,这就是为什么我说它不优雅。我的全部工作就是处理糟糕的设计。这真的令人沮丧,所以我不知道我还能做些什么。我也许可以告诉人们改变它,但那完全是另一回事。我很确定这将是我唯一一次使用它。很抱歉,我意识到我没有说清楚,并相应地改变了问题。这是一个我无法控制但必须使用的web服务。否则我会像一个优秀的程序员一样使用继承,或者更好,但不会有两个具有相同属性的独立类。它是一个部分类这一事实很有帮助,因为我可以在自己的代码中修改该类,而无需编辑代理文件,完全掩盖了这一点。谢谢