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

流过昼夜 提交于 2019-12-01 16:23:59

问题


Do static variables have the same or similar functionality in C# as they do in 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++?


回答1:


Static has multiple meanings in C++.

Static variables in C# basically only have a single meaning: variables scoped to a type. In C#, static on a type is used to denote a type-scoped variable. 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.

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. Globals and local static function variables are not supported in 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.




回答2:


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. In C#, static is only used to declare class-level entities.




回答3:


A static variable in C# behaves like a static member variable in c++. That is out of the multiple meanings of the 'static' keyword in c++ only one of Them exists in the context of C#. E.g. you can't limit the scope to a file with static (which is strictly a C feature) in C#



来源:https://stackoverflow.com/questions/2308681/what-is-the-difference-between-a-static-variable-in-c-vs-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!