我正在尝试做一项任务,但我没有这样做。我写了一个产品类,并用它做了一朵花。然后我想在花量低于20时举起一个事件,它应该给我一个警告。我想我很难举起这个活动。我确信我对代表和事件的判断是正确的,但缺少某些东西。先感谢您。
这一行
flower.StockDecreased();
给了我这个错误:
Error 3 The event 'StokTakip.Product.StockDecreased' can only appear on the left hand side of += or -= (except when used from within the type 'StokTakip.Product')
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StokTakip
{
class Program
{
static void FlowerStockDecreased()
{
Console.WriteLine("Flower stock decreased");
}
static void Main(string[] args)
{
Product flower = new Product("Flower", 50);
Console.WriteLine(flower);
flower.StockDecreased += new Product.FlowerEventHandler(FlowerStockDecreased);
while (true)
{
Console.WriteLine("What is your choice");
Console.WriteLine("[1] Stock entry quantity ");
Console.WriteLine("[2] Stock exit quantity: ");
int choice = Convert.ToInt32(Console.ReadLine());
if (choice == 1)
{
Console.Write("Enter stock entry quantity: ");
flower.quantity += Convert.ToInt32(Console.ReadLine());
}
else if (choice == 2)
{
Console.Write("Enter stock exit quantity: ");
flower.quantity -= Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine(flower);
if (flower.quantity<20)
{
flower.StockDecreased(); //????
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StokTakip
{
public class Product
{
public string name;
public int quantity;
public Product(string a, int m)
{
name = a;
quantity = m;
}
public override string ToString()
{
return "Name: "+ this.name + " Stock Quantity: " + this.quantity;
}
public delegate void FlowerEventHandler();
public event FlowerEventHandler StockDecreased;
}
}
答案 0 :(得分:3)
错误信息非常清楚。你不能举办这样的活动。只有声明类可以像这样调用事件,从而引发事件。所有其他类只能从事件中添加(+=
)或删除(-=
)事件处理程序。
你可以做的是将一个公共方法放入Product
类,引发这样的事件:
public void RaiseStockDecreased()
{
if (StockDecreased != null)
StockDecreased();
}
你可以在外面打电话。
但话又说回来,这与正确的设计相矛盾,因为我希望Product
类本身可以确定股票是增加还是减少,并提出适当的事件。否则,您必须在希望收到库存变化通知的每个地方实施该逻辑。
答案 1 :(得分:0)
您的产品类应如下所示:
public class Product
{
public event FlowerEventHandler StockDecreased;
private int _quantity;
public int Quantity
{
get { return _quantity; }
set
{
int newQuantity = value;
if (newQuantity < _quantity)
{
if (StockDecreased != null) StockDecreased();
}
_quantity = newQuantity;
}
}
// Other stuff
}
虽然更好的模式可能是StockChange
方法可以检查更改是正面还是负面,并引发相应的事件。