What's a neat solution to get property values ​​from two classes (that have the same property names) that don't use inheritance?

Basically I have to use a poorly implemented web service supported by other programmers. They have two classes that are not derived from the parent class, but have the same properties (Ughh ...). So this looks like in my web service proxy file:

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

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

      

So what's the best way to grab values ​​from known properties without duplicating code? I know I can probably use reflection, but that can get ugly. If there is an easier and crazier way to do this (perhaps in newer C # features?) Please let me know.

+2


a source to share


4 answers


I'm not sure I fully understand your situation, but maybe something like this? Define an interface IProduct

with methods getQuantity

and getPrice

and implement it in both classes:

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

      



And similarly for the other; then just use them like IProduct

.

+3


a source


If the classes are generated from a web proxy, you can implement a partial class that implements the common interface.

From the proxy generator:

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

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

      



Hand written:

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; } }
}

      

Both classes now implement IProduct

and can be passed in the same way.

+2


a source


Dynamic keyword in 4.0? but I wouldn't say it is graceful, but it will work.

+1


a source


here is some pseudocode, sorry for not working. Perhaps this gives you the right direction:

Object list = new list (); objects.Add (p1); // your first product object objects.Add (p2); // your second product object

    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
        //....
    }

      

0


a source







All Articles