简体   繁体   English

从main访问void中的变量

[英]Accessing a variable in a void from main

My Form1_Load: 我的Form1_Load:

private void Form1_Load(object sender, EventArgs e)
{
    Thread Usern = new Thread(new ThreadStart(Username));
    Usern.Start();
}

And my Username function: 和我的用户名功能:

public static void Username()
{
    try
    {
        string user = Environment.UserName;
        MessageBox.Show(user.ToString());
    }
    catch(Exception exc)
    { 
        MessageBox.Show(exc.Tostring()); 
    }
}

Anyone know how I would call "user" used in the function above ^ inside of Form_Load event? 任何人都知道如何调用Form_Load事件中^上方函数中使用的“用户”吗? I've tried changing the function return type to string but it says it's an invalid change. 我试过将函数返回类型更改为字符串,但它表示这是无效的更改。 I know that I could just copy and paste the code from the function into form_load event but it has to be in the function. 我知道我可以将函数中的代码复制并粘贴到form_load事件中,但它必须位于函数中。

Thank you guys in advance and sorry for such a "stupid question" as I didn't find anything related of my problem on SO. 在此先谢谢大家,对如此“愚蠢的问题”感到抱歉,因为我在SO上没有发现与我的问题有关的任何内容。

You should probably make user an instance variable instead of a local variable - in other words, declare it in your class: 您可能应该使user成为实例变量而不是局部变量-换句话说,在类中声明它:

private string user;

then in Username() (which should be renamed to DetectUserName or something similar) you would just have: 然后在Username() (应该重命名为DetectUserName或类似名称)中,您将只有:

user = Environment.UserName;

Your method should be an instance method though, so that it's associated with an instance of the class - remove the static keyword from the method declaration. 不过,您的方法应该是实例方法,以便它与类的实例相关联-从方法声明中删除static关键字。

It's not at all clear why you want to do this in a different thread though... 虽然还不清楚为什么要在另一个线程中执行此操作...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM