静态与非静态类成员 [英] Static vs non-static class members

查看:223
本文介绍了静态与非静态类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C锐利和编程一般。我有一个快速的问题 - 什么是关于静态/非静态变量的最佳实践。

I'm new to c sharp and programming generally. I have a quick question - what is best practise with regards to static/non static variables.

我有一个变量,私人诠释的x,属于Y级。要访问这个变量,我需要参考年。如果x是静态的,但我可以为y的引用访问这个变量。

I have a variable,private int x, which belongs to class y. To access this variable, i need to reference y. If x was static however, i can access this variable with no references to y.

这是去,在一个情况,即在Y类中的几个方法将引用这个值的最佳方式?

Which is the best way to go, in a situation whereby several methods within the class y will be referencing this value ?

希望这是有道理的,我的问题不是太简单了!

Hope this makes sense, and my question isn't too basic !

非常感谢

推荐答案

您需要考虑的静态变量属于的的,不要的实例的类

You need to think about static variables as belonging to the class, not to instances of the class.

如果在班级这个变量应该是相同的所有实例,使用一个静态变量。

If, in all instances of the class this variable should be identical, use a static variable.

如果不是,请使用一个实例变量。

If not, use an instance variable.

在一般公众有静态变量为坏习惯 - 这是一个全球共享资源,如果你改变它,你需要同步访问它。拥有全局状态是你想避免尽可能多的东西。

In general having public static variables is bad practice - it is a shared global resource and if you change it you need to synchronize access to it. Having global state is something you want to avoid as much as possible.

这篇关于静态与非静态类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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