我有一个简单的问题。有一个基类Product。和派生类,如手环,耳环和环。但是ring类有一个额外的属性。
在下面代码中,我如何达到size属性并在方法中使用它。
public class Product
{
public int id;
public string title;
}
public class Bracelet : Product
{
}
public class Earring : Product
{
}
public class Ring : Product
{
public int size;
}
Product product;
if(category = 1) // this is a Bracelet
{
product = new Bracelet();
}
else if(category = 2) // this is a Earring
{
product = new Earring();
}
else if(category = 3) // Wola, this is a ring
{
product = new Ring();
product.size = 4; // I cant reach size.. I need to assign size of the ring to decrease stock correctly.
}
product.decreaseStock();发布于 2012-06-14 07:18:06
只需先在本地声明该值:
else if (category == 3)
{
var ring = new Ring();
ring.size = 4;
product = ring;
}这样,您就可以在if块中以Ring的形式访问该变量,但它还会将它赋给更通用的product变量。
或者,您可以只使用初始化器语法:
else if (category == 3)
{
product = new Ring { size = 4 };
}发布于 2012-06-14 07:23:16
Kirk Woll的答案可能是最好的,但另一个解决方案是使用'as‘关键字:
(product as Ring).size = 4;或者铸造它:
((Ring)product).size = 4;另外,请确保不要将赋值运算符(=)与相等运算符(==)混淆。例如,它应该是if(类别== 3)
发布于 2012-06-14 07:20:42
您必须重写Ring中的decreaseStock方法。
因此,在产品中,首先将减少库存方法标记为虚拟。
public class Product
{
public int id;
public string title;
public virtual void DecreaseStock()
{
//your decrease logic here
}
}然后在ring中,将考虑到大小的新逻辑放在覆盖方法中
public class Ring : Product
{
public int size;
public override void DecreaseStock()
{
//your special logic to deal with size here
}
}https://stackoverflow.com/questions/11024669
复制相似问题