我无法找到与我匹配的特定问题,我认为这与我使用一个参数(字符串)创建EventArgs的子类这一事实有关。当我尝试编译时,它似乎告诉我ScanInfoEventArgs没有一个构造函数,当它显然(至少对我来说)。
我只包含了我认为适用的代码。看起来这么简单,我不知所措。
public partial class MainWindow : Window
{
Coffee coffeeOnHand;
SweetTea sweetTeaOnHand;
BlueberryMuffin blueberryMuffinOnHand;
public MainWindow()
{
InitializeComponent();
//The following reads the inventory from file, and assigns each inventory item to the Coffee, SweatTea
//and BlueberryMuffin objects in memory.
using (Stream input = File.OpenRead("inventory.dat"))
{
BinaryFormatter formatter = new BinaryFormatter();
coffeeOnHand = (Coffee)formatter.Deserialize(input);
sweetTeaOnHand = (SweetTea)formatter.Deserialize(input);
blueberryMuffinOnHand = (BlueberryMuffin)formatter.Deserialize(input);
}
//The following adds whatever information is loaded from the objects on file from above
//into the dropdown box in the menu.
SelectedItemDropdown.Items.Add(coffeeOnHand);
SelectedItemDropdown.Items.Add(sweetTeaOnHand);
SelectedItemDropdown.Items.Add(blueberryMuffinOnHand);
}
public class ScanInfoEventArgs : EventArgs
{
ScanInfoEventArgs(string scanType)
{
this.scanType = scanType;
}
public readonly string scanType;
}
public class Scan
{
//Delegate that subscribers must implement
public delegate void ScanHandler (object scan, ScanInfoEventArgs scanInfo);
//The event that will be published
public event ScanHandler onScan;
public void Run()
{
//The ScanInfoEventArgs object that will be passed to the subscriber.
ScanInfoEventArgs scanInformation = new ScanInfoEventArgs("scanType");
// Check to see if anyone is subscribed to this event.
if (onScan != null)
{
onScan(this, scanInformation);
}
}
}
答案 0 :(得分:6)
您需要创建构造函数public
。所有班级成员都默认为private
,这意味着外界无法接触到他们。
由于编译器没有看到匹配的 public 构造函数(因为代码实际上可以调用一个),它会抛出你看到的错误。
正确的代码:
public ScanInfoEventArgs(string scanType)
{
this.scanType = scanType;
}
请注意,如果所有代码都驻留在同一个程序集中,internal
也可以正常工作。