gpt4 book ai didi

c# - Parameterless constructor constructor less 类(来自另一个程序集)

转载 作者:太空宇宙 更新时间:2023-11-03 23:12:45 27 4
gpt4 key购买 nike

我有一个来自 NuGet 包的类:

using System.Windows.Forms;

namespace FMUtils.KeyboardHook
{
public class KeyboardHookEventArgs
{
public bool isRShiftPressed { get; }
public bool isRWinPressed { get; }
public bool isShiftPressed { get; }
public bool isWinPressed { get; }
public Keys Key { get; }

public override string ToString();
}
}

它在一个程序集中,然后被这个程序引用:

using System;
using System.Windows.Forms;
using FMUtils.KeyboardHook;

namespace SpeedyGonzales
{
public class MyClass
{
public MyClass()
{
var key = new KeyboardHookEventArgs();
}
}
}

这在编译时中断,给我这个错误:

'KeyboardHookEventArgs' does not contain a constructor that takes 0 arguments

关于这个问题,我发现了几件事:

  1. 每个类都需要一个构造函数
  2. 如果您没有显式提供任何构造函数,将调用直接父级的无参数构造函数
  3. 如果父级没有这样的构造函数,则抛出错误

这似乎是我的情况,但由于我的类没有继承任何东西,这意味着唯一的直接父对象是..对象?对象没有无参数构造函数吗?请澄清。

最佳答案

您问题中显示的源代码与 source in the NuGet package 不匹配. KeyboardHookEventArgs 类实际上包含一个带有参数的构造函数。此构造函数的签名如下所示:

internal KeyboardHookEventArgs(FMUtils.KeyboardHook.Hook.KBDLLHOOKSTRUCT lParam)

构造函数被标记为 internal,即它在包含声明的程序集之外是不可见的(这就是您可能在 Visual Studio 中看不到它的原因)。因此,您不能直接在代码中创建 KeyboardHookEventArgs 类型的对象。这可能是该库的作者的意图(因为他明确声明了内部构造函数)。

intended usage就是使用Hook类来创建钩子(Hook)。如您所见,KeyboardHookEventArgs 类型的对象随后由 Hook 类创建,并作为事件处理程序的参数传递给您的代码:

var KeyboardHook = new Hook("Global Action Hook");
KeyboardHook.KeyDownEvent += KeyDown;
// Also: KeyboardHook.KeyUpEvent += KeyUp;

private void KeyDown(KeyboardHookEventArgs e)
{
// handle keydown event here
// Such as by checking if e (KeyboardHookEventArgs) matches the key you're interested in

if (e.Key == Keys.F12 && e.isCtrlPressed)
{
// Do your magic...
}
}

关于c# - Parameterless constructor constructor less 类(来自另一个程序集),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38476389/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com