私は与えられた課題を実行しようとしていますが、失敗しています。私は製品クラスを書いてそれから花を作りました。花量が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;
}
}
これはエラーメッセージです。 publicメンバー 'StockDecreased'は、追加と削除という2つのメソッドしか提供しません。イベントを所有しているクラス以外の場所からイベントを呼び出すことはできません。 – Luaan