【发布时间】:2015-05-04 20:35:51
【问题描述】:
我找不到与我匹配的特定问题,我认为这与我正在使用一个参数(一个字符串)创建 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);
}
}
}
【问题讨论】:
-
我想我以前从来没有这样做过。我使用“:base()”作为构造函数?
-
没关系。我昨天才发现总是调用任何派生类型的无参数构造函数,所以你很好。但是如果你有一个重载的构造函数,你想将参数传递给基类,你会做类似
ScanInfoEventArgs(object source, string scanType) : base(source)的事情。当然,这在这种情况下不起作用,因为EventArgs没有接受对象的构造函数,但这只是为了说明目的。
标签: c#