首页 > 解决方案 > 为什么我可以在静态主函数中使用类成员变量?

问题描述

据我所知,静态函数不允许在 C# 中使用任何静态变量,对吧? Main()函数是静态函数,但我一直在使用我自己的类。

例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        public int size = 300;

        static void Main(string[] args)
        {
            Test t = new Test();

            // this is error
            size = 500;

            // why this is not error, despite Test Class's object's member length is not a static member?
            // i think that Main is static if so length variable shouldn't it be static ?
            t.length = 300;
        }
    }

    class Test
    {
       public int length;  
    }
}

标签: c#

解决方案


静态变量在类的生命周期中仅初始化一次,而非静态变量会初始化 0 次或 n 次,具体取决于为该类创建的对象数量。

在 c# 中使用静态和非静态成员时要遵循的规则:

  1. 非静态到静态:只能通过使用该类的对象来使用。
  2. 静态到静态:可以直接使用,也可以使用类名。
  3. 静态到非静态:可以直接使用,也可以使用类名。
  4. 非静态到非静态:可以直接使用,也可以使用“this”关键字。

请参阅此链接以清楚地了解 C# 中的静态和非静态成员。


推荐阅读