C#在类之间共享或修改变量 [英] C# share or modify variables between classes

查看:85
本文介绍了C#在类之间共享或修改变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有2类:计时器和钥匙钩.

So I have 2 classes: Timers and KeyHook.

在Timers类中,我有一个称为DateTime类型的名为lastInteraction的公共变量.

In the Timers class I have a public variable called lastInteraction of type DateTime.

KeyHook类负责侦听键盘事件.当前,当按下一个键时,它会打印到屏幕上.

The KeyHook class is responsible for listening to keyboard events. Currently it prints to the screen when a key is pressed.

我希望KeyHook事件用当前的DateTime更新lastInteraction变量,这可能吗?即使我在计时器类中创建KeyHook实例也无济于事.

I want the KeyHook event to update the lastInteraction variable with the current DateTime, is that possible? Even if I create the KeyHook instance within the timer class it doen't help.

我如何在线上搜索,但是据我所知,一个变量不能在类之间共享,并且在类之间传递值是行不通的.

How can I achieve such thing, I serached online but to the best of my knowledge a variable can't be shared across classes and passing the values around between classes won't work.

一些代码段:

Program.cs

static void Main(string[] args)
{
    BeatW.Timers timer = new BeatW.Timers();
    timer.startTimers();

    KeyHook kh = new KeyHook();

    Console.ReadKey();
}

KeyHook.cs

public static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
    {
        int vkCode = Marshal.ReadInt32(lParam);
        Console.WriteLine((Keys)vkCode);
    }
    return CallNextHookEx(_hookID, nCode, wParam, lParam);
}

Timers.cs

class Timers
{
    public DateTime lastInteraction;
    ...
}

推荐答案

如果您设置了静态类,则可以做您想做的事情.

If you set a static class it is possible to do what you want to.

public static class Timers
{
    public static DateTime lastInteraction { get; set; }
    ...
}

在KeyHook类中,您可以在其上放置值.

And in the KeyHook class you can put values on it.

public static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
    {
        int vkCode = Marshal.ReadInt32(lParam);
        >>>>>Timers.lastInteraction = DateTime.Now;
        Console.WriteLine((Keys)vkCode);
    }
    return CallNextHookEx(_hookID, nCode, wParam, lParam);
}

并且您可以在运行时在所有命名空间范围内访问 Timers.lastInteraction 的值.

And you can access the value of Timers.lastInteraction on all namespace range at runtime.

这篇关于C#在类之间共享或修改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆