![](/img/trans.png)
[英]Create an class or an object that can have different properties everytime in C#
[英]C# - How to have a dictionary of different class properties
假設我有這堂課
public class Fruit
{
//all the fruit types
public string apple;
public string orange;
public string grape;
}
我想要一本可以添加Fruit屬性的字典。 Dictionary<Fruit, string> fruitDict
我可以在其中執行fruitDict.add(Fruit.apple,“ 1”)或fruitDict.add(orange, "2")
。 設計此的最佳方法是什么? 使我的財產枚舉的最好方法嗎?
根據我對水果的了解,我猜您實際上是在尋找可以容納三種水果的列表,如下所示:
abstract class Fruit
{
}
class Apple : Fruit
{
}
class Orange : Fruit
{
}
class Grape : Fruit
{
}
var fruitList = new List<Fruit>
{
new Apple(),
new Orange(),
new Grape()
};
另一方面,如果您真的想要一個可以包含各種水果的類,則可能是您想要的:
enum FruitType { Apple, Grape, Orange }
class FruitBasket : Dictionary<FruitType,int>
{
public void AddFruit(FruitType fruitType, int count)
{
if (!this.ContainsKey(fruitType))
{
this.Add(fruitType, 0);
}
this[fruitType] += count;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.