【问题标题】:EventArgs does not contain a constructor that takes 1 argumentEventArgs 不包含采用 1 个参数的构造函数
【发布时间】: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#


【解决方案1】:

你需要让你的构造函数public。所有班级成员默认为private,即外界无法接触到他们。

由于编译器没有看到匹配的 public 构造函数(如代码实际调用的构造函数),它抛出了您看到的错误。

正确代码:

    public ScanInfoEventArgs(string scanType)
    {
        this.scanType = scanType;
    }

请注意,如果所有代码都位于同一个程序集中,internal 也可以正常工作。

【讨论】:

  • 天哪,非常感谢!我以为因为类本身是公开的,所以方法也是公开的,但现在我想,这没有任何意义。
猜你喜欢
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
相关资源
最近更新 更多