简体   繁体   English

需要对象引用C#CS0120

[英]An object reference is required C# CS0120

This question has been asked to death but i cannot take from those answers what my problem is. 这个问题被问到死了,但是我不能从那些答案中得出我的问题是什么。

All i want to do is : 我要做的就是:

  1. Declare my global bool variable (used as a flag for later.) 声明我的全局布尔变量(以后用作标记)。
  2. Run my method to do a check, in which it will change the global variable 运行我的方法进行检查,它将更改全局变量

Anybody able to explain why this isn't working? 有人能解释为什么这行不通吗? Thanks. 谢谢。

    class Program
    {
        public bool onVPN;

         static void Main(string[] args)
        {
            CheckVPN();
            CheckIfInternal();
            Console.WriteLine("Press enter to close...");
            Console.ReadLine();
        }
        public void CheckVPN()
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                //crude way to check if the VPN adapter is running
                if (adapter.Description == "VPN Adapter")
                {
                   onVPN = true;
                }

                else
                {
                    onVPN = false;
                }

            }
        }
class Program
{
    public static bool onVPN;

     static void Main(string[] args)
    {
        CheckVPN();
        CheckIfInternal();
        Console.WriteLine("Press enter to close...");
        Console.ReadLine();
    }
    public static void CheckVPN()
    {
        NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface adapter in adapters)
        {
            //crude way to check if the VPN adapter is running
            if (adapter.Description == "VPN Adapter")
            {
               onVPN = true;
            }

            else
            {
                onVPN = false;
            }

        }
    }

Changes applied, are added static keyword to onVPN field, and to method CheckVPN . 应用的更改被添加到onVPN字段和方法CheckVPN static关键字。

More explanation can be found here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0120 可以在这里找到更多说明: https : //docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/compiler-messages/cs0120

you have 2 options here 您在这里有2个选择

1.change CheckVPN() signature to static and the variable onVPN to static as well, you can find the reason why you have to add static here 1.将CheckVPN()签名更改为static并将onVPN变量也onVPN为static,您可以在此处找到添加static的原因

2.create new class and put your code there as it is, and then on your main class you can do something like this 2.创建一个新类,并将您的代码原样放置在那里,然后在您的主类上,您可以执行以下操作

Class1 c = new Class1();
c.CheckVPN();

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

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