【发布时间】:2010-12-19 11:24:46
【问题描述】:
我有三门课;实现接口 IProduct 的 Stamp、Letter 和 Parcel,它们也有一些自己的功能。
public interface IProduct
{
string Name { get; }
int Quantity { get; set; }
float Amount { get; }
}
public class Stamp : IProduct
{
public string Name { get { return "Stamp"; } }
public int Quantity { get; set; }
public float Amount { get; set; }
public float UnitPrice { get; set; }
}
public class Letter : IProduct
{
public string Name { get { return "Letter"; } }
public int Quantity { get; set; }
public float Amount { get; set; }
public float Weight { get; set; }
public string Destination { get; set; }
}
public class Parcel : IProduct
{
public string Name { get { return "Parcel"; } }
public int Quantity { get; set; }
public float Amount { get; set; }
public float Weight { get; set; }
public string Destination { get; set; }
public int Size { get; set; }
}
public static class ShoppingCart
{
private static List<IProduct> products = new List<IProduct>();
public static List<IProduct> Items { get { return products; } }
}
为什么我不能从 List<IProduct> 访问派生类的其他成员?
ShoppingCart.Items.Add(new Stamp { Quantity = 5, UnitPrice = 10, Amount = 50 });
ShoppingCart.Items.Add(new Letter { Destination = "US", Quantity = 1, Weight = 3.5f });
ShoppingCart.Items.Add(new Parcel { Destination = "UK", Quantity = 3, Weight = 4.2f, Size = 5 });
foreach (IProduct product in ShoppingCart.Items)
{
Console.WriteLine("Name: {0}, Quantity: {1}, Amount: {2}", product.Name, product.Quantity, product.Amount);
}
我曾想过使用泛型,但在这种情况下,我将不得不为每种特定类型的产品编写单独的代码。
public static class ShoppingCart<T> where T : IProduct
{
private static List<T> items = new List<T>();
public static List<T> Items { get { return items; } }
}
ShoppingCart<Stamp>.Items.Add(new Stamp { Quantity = 5, Amount = 10, UnitPrice = 50 });
ShoppingCart<Letter>.Items.Add(new Letter { Destination = "US", Quantity = 1, Weight = 3.5f });
foreach (Stamp s in ShoppingCart<Stamp>.Items)
{
Console.WriteLine("Name: {0}, Quantity: {1}, Amount: {2}", s.Name, s.Quantity, s.Amount);
}
foreach (Letter l in ShoppingCart<Letter>.Items)
{
Console.WriteLine("Name: {0}, Destination: {1}, Weight: {2}", l.Name, l.Destination, l.Weight);
}
这种问题没有任何设计模式。工厂模式?
【问题讨论】:
-
我的问题是,如果你的接口只有成员而不是方法,那么它的意义何在?您只是在重新定义每个类中的那些成员。
-
接口必须要有方法吗?
-
不,这不是必须的,但通常您使用接口来遵守合同。合同通常是需要通过签署该合同的类来实现的方法。当您在接口中有签名者必须实现它们的方法时。当涉及到变量本身并且只有变量时,创建接口是否有意义?
-
你说得对,JonH :)
-
那些不是真正的变量或方法。它们是属性,是一系列方法(getter 和 setter)的语法细节。有一个通用的 i/f 为这种用途定义它们是完全合法和有用的——所有 impl 必须在给定上下文中有用的某些属性。典型的方法是还有一个通用的抽象基类 (
BaseProduct),它实现了IProduct并且所有产品实现都派生自该类。
标签: c# generics interface derived-class