我们不能在C#中的函数中声明静态变量,而我们能够用c语言声明。为什么? [英] we can't declare static variable with in a function in C#, while we were able to declare in c language. why?

查看:256
本文介绍了我们不能在C#中的函数中声明静态变量,而我们能够用c语言声明。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们不能在C#中的函数中声明静态变量,而我们能够用c语言声明。为什么?

解决方案

因为我们并不真的需要它们。或者我们不应该,无论如何。



C函数中静态变量的目的是保留函数执行的值,而不是将其显示给外面的世界。它基本上是一个快捷方式,用于在函数外部声明变量,其名称仅在函数体内有效。



C#不允许它,因为它提供了不同的model - 一种不同的思维方式 - 它在类实例的基础上保留变量,而不必让它们在函数的基础上使用。它在C#中更灵活 - 你得到了类似的效果,打开了全班,但是限制在那个类中,所以它不能被外界看到。


你不能有一个静态的C#变量,但你可以有一个静态成员:字段或属性,这要好得多,而且足够了。为什么?因为C#不像C和C ++那样不安全和草率。哲学是完全不同的。顺便说一句,即使静态成员也应该很少使用并且要小心,无论是C#,C还是C ++。特别是,您是否了解静态内存对线程的影响?这是一个非常严重的威胁。



参见:

http://en.wikipedia.org/wiki/Singleton_pattern [ ^ ],

http://csharpindepth.com/Articles/一般/ Singleton.aspx [ ^ ](这个C#实现很好,但是我看到很多坏的,所以要特别注意这个代码,特别是对于它的线程方面)。



-SA

we can't declare static variable with in a function in C#, while we were able to declare in c language. why?

解决方案

Because we don't really need them. Or we shouldn't, anyway.

The purpose of a static variable in a C function is to preserve the value across executions of the function, without revealing it to the outside world. It's basically a shortcut for declaring the variable outside the function with a name that only works inside the function body.

C# doesn't allow it, because it provides a different model - a different way of thinking - and it preserves variables on an class instance basis instead of having to let them be used on a function basis. It's more flexible in C# - you get a similar effect, opened up to the whole class, but restrictable to within that class so it can't be seen by the outside world.


You cannot have a static C# variable, but you can have a static member: field or property, which is much better and is quite enough. Why? Because C# is not that unsafe and sloppy as C and C++. The philosophy is quite different. By the way, even static members should be used very rarely and with caution, no matter if this is C#, C or C++. In particular, do you understand implications of static memory on threading? This is a very serious threat.

See also:
http://en.wikipedia.org/wiki/Singleton_pattern[^],
http://csharpindepth.com/Articles/General/Singleton.aspx[^] (this C# implementation is good, but I saw a lot of bad once, so pay special attention for this code, especially for threading aspects of it).

—SA


这篇关于我们不能在C#中的函数中声明静态变量,而我们能够用c语言声明。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆