C#中的类似C的静态代码? [英] c-like static in c#?
问题描述
大家好
我想问一下是否有可能在c#中有一种行为类似于c ++中的静态局部变量,
我的意思是我想在一个方法中有一个局部变量,该变量是在第一次调用该方法时分配(初始化)的,而在一次又一次地调用该方法之后,它将不会再次初始化,并保持其值与我上次的时间相同调用了方法
谢谢
Hi all
i wanted to ask if it is possible to have a kind of variable in c# that behave like static local variable in c++,
I mean I want to have a local variable in a method, that it is assigned (initialize) just the first time the method invoked and after calling the method again and again it would not be initialize again and keep its value from the last time I invoked the method
thank you
推荐答案
您在说的是这样的:
What you are talking about is something like this:
void SomeFunction(void)
{
static int sVar = 1;
...
}
可以在 C 和 C ++ 中执行此操作,但是在 C#中则无法执行.请注意, C 语言不是面向对象,并且 C ++ 是多范式语言.
C#是一种纯粹的面向对象语言,您尝试做的事情违反了 OOP 的原理:如果您需要一种方法来保留某些内容调用之间的状态,则应使该状态变量成为包含该方法的类的成员.
请注意,另一种语言可能不允许使用某种编程语言进行操作.再者,一种编码风格可能对一种语言有利,而对另一种语言不利.
It is possible to do this in C and C++, but it is not possible in C#. Be aware that the C language is not object oriented and the C++ is a multi paradigm language.
The C# is a pure object oriented language and what you are trying to do break the principles of OOP: if you need a method to persist some state between calls, you should make that state variable a member of the class that contains the method.
Be aware that things that are possible with a programming language, could be not allowed by another language. And again, a coding style could be good with a language and bad with another.
如果您不希望在初始化后将其声明为static readonly
,请对其进行更改.如果您希望以后可以更改它,但又保留实例之间的值,只需将其标记为static
.
If you don''t want it to change after initialization declare itstatic readonly
. If you want to be able to change it later but have it retain the value between instances just mark itstatic
.
我希望它是本地的,并且不允许在本地范围内使用完全使用静态关键字,不是吗?
I want it to be local and in local scope we are not allowed to use static keyword at all, isn''t it?
这篇关于C#中的类似C的静态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!