c#设计一个水果篮子
时间: 2023-12-14 10:30:27 浏览: 56
好的,设计一个水果篮子可以使用面向对象的思想,首先我们可以定义一个Fruit类,包含水果的名称、颜色、重量等属性,然后定义一个Basket类,包含水果篮子的容量、当前水果数量、添加水果、移除水果等方法。具体实现可以参考以下代码:
```csharp
class Fruit
{
public string Name { get; set; }
public string Color { get; set; }
public double Weight { get; set; }
}
class Basket
{
private int capacity;
private int count;
private List<Fruit> fruits;
public Basket(int capacity)
{
this.capacity = capacity;
this.count = 0;
this.fruits = new List<Fruit>();
}
public void AddFruit(Fruit fruit)
{
if (count < capacity)
{
fruits.Add(fruit);
count++;
Console.WriteLine("Add {0} to the basket.", fruit.Name);
}
else
{
Console.WriteLine("The basket is full.");
}
}
public void RemoveFruit(Fruit fruit)
{
if (fruits.Contains(fruit))
{
fruits.Remove(fruit);
count--;
Console.WriteLine("Remove {0} from the basket.", fruit.Name);
}
else
{
Console.WriteLine("The basket does not contain {0}.", fruit.Name);
}
}
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)