c# - 为什么我可以在静态主函数中使用类成员变量?
问题描述
据我所知,静态函数不允许在 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;
}
}
解决方案
静态变量在类的生命周期中仅初始化一次,而非静态变量会初始化 0 次或 n 次,具体取决于为该类创建的对象数量。
在 c# 中使用静态和非静态成员时要遵循的规则:
- 非静态到静态:只能通过使用该类的对象来使用。
- 静态到静态:可以直接使用,也可以使用类名。
- 静态到非静态:可以直接使用,也可以使用类名。
- 非静态到非静态:可以直接使用,也可以使用“this”关键字。
请参阅此链接以清楚地了解 C# 中的静态和非静态成员。
推荐阅读
- shopware - Shopware 默认产品滑块的附加条件
- unit-testing - 如何在角度测试用例中对 localStorage 和订阅功能项进行代码覆盖
- java - 代码意外停止而不是无限运行
- python - 将没有返回值的 Python Lambda 函数转换为 Pyspark
- javascript - 放大 - 在悬停缩略图库中
- node.js - AWS SQS 套接字挂断间歇性错误
- jquery - 根据元素的位置更改元素类
- jenkins - 如何在 Jenkins 中执行 Liquibase 脚本而不将 liquibase 插件安装为 shell 脚本
- bash - 寻找 ENV 变量的存在
- python - 如何接收 cmd 'quser' 输出?