简体   繁体   English

C ++与C#中的静态变量有什么区别?

[英]What is the difference between a static variable in C++ vs. C#?

Do static variables have the same or similar functionality in C# as they do in C++? 静态变量在C#中具有与在C ++中相同或相似的功能吗?

Edit: 编辑:

With C++ you can use static variables in many different contexts - such as: 1) Global variables, 2) Local function variables, 3) Class members - Would similar usages in C# behave similar to that of C++? 使用C ++,您可以在许多不同的上下文中使用静态变量 - 例如:1)全局变量,2)本地函数变量,3)类成员 - C#中的类似用法是否与C ++类似?

Static has multiple meanings in C++. 静态在C ++中有多种含义。

Static variables in C# basically only have a single meaning: variables scoped to a type. C#中的静态变量基本上只有一个含义:变量作用于一个类型。 In C#, static on a type is used to denote a type-scoped variable. 在C#中,类型上的静态用于表示类型范围的变量。 Static on a method is a type-scoped method. 方法上的静态是类型范围的方法。 Static can also be used on a class to denote that the entire class is comprised only of static methods, properties, and fields. Static也可以在类上使用,表示整个类只包含静态方法,属性和字段。

There is no equivelent to static variables within a function scope, or non-class scoped static values. 函数作用域内的静态变量或非类作用域静态值不存在等价。


Edit: 编辑:

In reponse to your edit, C# basically only uses static for class members. 响应编辑,C#基本上只对类成员使用静态。 Globals and local static function variables are not supported in C#. C#不支持全局和局部静态函数变量。 In addition, as I mentioned above, you can flag an entire class "static", which basically just makes the compiler check that there are no non-static members in the class. 另外,正如我上面提到的,你可以标记整个类“静态”,这基本上只是让编译器检查类中没有非静态成员。

From MSDN: The static keyword: In C++, static can be used both to declare class-level entities and to declare types that are specific to a module. 来自MSDN: static关键字:在C ++中,static既可用于声明类级实体,也可用于声明特定于模块的类型。 In C#, static is only used to declare class-level entities. 在C#中,static仅用于声明类级实体。

A static variable in C# behaves like a static member variable in c++. C#中的静态变量的行为类似于c ++中的静态成员变量。 That is out of the multiple meanings of the 'static' keyword in c++ only one of Them exists in the context of C#. 这是c ++中'static'关键字的多重含义,只有其中一个存在于C#的上下文中。 Eg you can't limit the scope to a file with static (which is strictly a C feature) in C# 例如,你不能将范围限制为C#中带静态(严格来说是C特性)的文件

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

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