What's an elegant solution to get the property values from two classes (that have the same property names) that do not use inheritance?
Essentially I have to use a poorly implemented web service maintained by other programmers. They have two classes that don't derive from a parent class, but have the same properties (Ughh...). So it looks like this in my web service proxy class file:
public partial class Product1
{
publ开发者_如何学JAVAic int Quantity;
public int Price;
}
public partial class Product2
{
public int Quantity;
public int Price;
}
So what's the best way to grab the values from known properties without duplicating the code? I know I probably could use reflection, but that can get ugly. If there is an easier less crazier way to do it (maybe in the new c# features?) please let me know.
I'm not sure I fully understand your situation, but maybe something like this?
Define an IProduct
interface with getQuantity
and getPrice
methods, 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 one; then just use them both as IProduct
.
If the classes are generated from a web proxy, then you could implement a partial class that implemented a common interface.
From Proxy Gen:
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; } }
}
Now both your classes implement IProduct
and can be passed around the same way.
Dynamic keyword in 4.0? but I wouldn't say it's elegant, but it will work.
here is some pseudocode sorry for don't working it out. Maybe this gives you the right direction:
List objects = 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
//....
}
精彩评论