简体   繁体   English

静态与非静态类成员

[英]Static vs non-static class members

I'm new to c sharp and programming generally.我是 C 锐利和编程的新手。 I have a quick question - what is best practise with regards to static/non static variables.我有一个简单的问题 - 关于静态/非静态变量的最佳实践是什么。

I have a variable,private int x, which belongs to class y.我有一个变量,私有 int x,它属于 y 类。 To access this variable, i need to reference y.要访问此变量,我需要引用 y。 If x was static however, i can access this variable with no references to y.但是,如果 x 是静态的,我可以在不引用 y 的情况下访问此变量。

Which is the best way to go, in a situation whereby several methods within the class y will be referencing this value ?在 y 类中的多个方法将引用此值的情况下,哪种方法最好?

Hope this makes sense, and my question isn't too basic !希望这是有道理的,我的问题不是太基本!

Many thanks非常感谢

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.拥有全局状态是您想要尽可能避免的事情。

Best practice is to avoid public static.最佳实践是避免公共静态。 In OOP, class is meant to hide its members.在 OOP 中,类旨在隐藏其成员。 Static is actually not a member of the instance but of the type . Static 实际上不是实例的成员,而是类型的成员。

Static comes handy if you are implementing singleton pattern.如果您正在实施单例模式,静态会派上用场。 But then again they need to be made private and accessible through a public property.但话又说回来,它们需要私有化并通过公共财产访问。

You need to read Static Classes and Static Class Members (C# Programming Guide) .您需要阅读静态类和静态类成员(C# 编程指南)

Well I can't conclusively say that one is better, because they serve different purposes.好吧,我不能最终说一个更好,因为它们用于不同的目的。

Are you familiar with OOP?你熟悉OOP吗? In OOP, static objects or members of a class that can be accessed directly from the class, while non-static members can only be accessed from the instance it belongs to.在 OOP 中,静态对象或类的成员可以直接从类中访问,而非静态成员只能从其所属的实例中访问。

C# follows a similar principle for the methods. C# 遵循类似的方法原则。 The static methods can by accessed directly from the class, while non-static methods (or instance methods as I like to call them) have to be accessed from an instance.静态方法可以直接从类中访问,而非静态方法(或我喜欢称之为实例方法)必须从实例中访问。 That is why instatiating needs to be done for instance methods, while for static methods it's just not needed, and furthermore impractical (see below).这就是为什么需要对实例方法进行实例化,而对于静态方法则不需要它,而且也不切实际(见下文)。

In OOP, static variables are used for values which cannot be stored by an instance variable.在 OOP 中,静态变量用于不能由实例变量存储的值。 Example: supposed you wanted to keep a count of how many instances of a class exists?示例:假设您想计算一个类的实例数量? How would you store that in a single instance?您将如何将其存储在单个实例中?

The methods use a similar principle.这些方法使用类似的原理。 They should be used for procedures for which it is impractical to do within an instance of a class.它们应该用于在类的实例中不切实际的过程。 I tend to use them for broad procedures (not a technical term), meaning those that do not require me to instantiate an object.我倾向于将它们用于广泛的过程(不是技术术语),意思是那些不需要我实例化对象的过程。 Example, adding two parameters.例如,添加两个参数。 (This usage may or may not be correct, but I believe it is) (这种用法可能正确也可能不正确,但我相信它是)

However, if you wanted to add two properties of an object, the method cannot be static, because as you would soon realize, static methods cannot access instance methods or variables within a class.但是,如果要添加对象的两个属性,则该方法不能是静态的,因为您很快就会意识到,静态方法无法访问类中的实例方法或变量。 Of course that makes sense because that static method would not know which instance of the class the get these from unless it were told, since it is not part of an instance itself)当然这是有道理的,因为除非被告知,否则静态方法不知道从类的哪个实例获取这些,因为它不是实例本身的一部分)

For the sake of no further complicating things, I'll stop here.为了不让事情变得更复杂,我就到此为止。 Let me know if you misunderstood anything.如果您误解了什么,请告诉我。

Your choice depends on your architecture.您的选择取决于您的架构。

Static makes part of a Type , others make part of an instance of that type. Static成为Type 的一部分,其他人则成为该类型实例的一部分。 If you want have some shared state (say) between different instances of the same type, use static .如果您希望在相同类型的不同实例之间有一些共享状态(比如),请使用static If you want that every instance have it's own value, independent from others, use instance fields.如果您希望每个实例都有自己的值,独立于其他instance ,请使用instance字段。

In both cases, by the way, avoid to expose like a public fields , but use properties.在这两种情况下,顺便说一下,避免像公共fields那样公开,而是使用属性。

I completely agree with Mr Oded :我完全同意奥德先生的观点

If, in all instances of the class this variable should be identical, use a static variable.如果在类的所有实例中该变量都应该相同,则使用静态变量。

If not, use an instance variable.如果没有,请使用实例变量。

Yes, adding static to a class member basically means you can access it without an instance, and only outside any instance.是的,向类成员添加static基本上意味着您可以在没有实例的情况下访问它,并且只能在任何实例之外访问它。 And yes, it becomes a global resource , or even a global variable if you will.是的,它变成了一个全局资源,如果你愿意,它甚至是一个全局变量

But I think there's at least another ( heavily edited ) good point to be made here...但我认为这里至少还有另一个(经过大量编辑的)好点……

Using static members as global vars go against OOP使用静态成员作为全局变量违背OOP

This means once you set a static member you can't pass it around as an object.这意味着一旦你设置了一个静态成员,你就不能将它作为对象传递。 The more you use static as global var, the more difficult it is for unit testing / mock ing classes .使用 static 作为全局变量越多,单元测试/模拟就越困难。

There is a solution for that, Singletons .有一个解决方案, Singletons But they should never come without warnings !但他们不应该没有警告

At other hand, if you're sure you really need global vars, take a look at the Toolbox pattern .另一方面,如果您确定确实需要全局变量,请查看Toolbox模式 It's a not well known extension of Singleton pattern.这是单例模式的一个鲜为人知的扩展。 It's so unknown in fact, if you google for it you won't find it with those keywords ( toolbox pattern ).事实上,它是如此未知,如果你用谷歌搜索它,你不会用那些关键字(工具箱模式)找到它。

So plan ahead.所以提前计划。 Read more.阅读更多。 Get to know about every option so you can decide better.了解每个选项,以便您做出更好的决定。 Even get a book.甚至得到一本书。 Object Oriented Programming is more about applying concepts that will help in the long run than just making things work now.面向对象编程更多是关于应用从长远来看有帮助的概念,而不仅仅是让事情现在起作用。

In general if you want to have a variable public, either static or instance, you must wrap it in a property and expose it like that.一般来说,如果你想要一个变量 public,无论是静态的还是实例的,你必须将它包装在一个属性中并像这样公开它。 This is for sure a principle that you will love to follow.这肯定是一个你会喜欢遵循的原则。

But despite some of the other answers I cannot say don't use static.但是尽管有其他一些答案,我不能说不要使用静态。 Static is not the devil that you should avoid in any case.在任何情况下,静态都不是您应该避免的魔鬼。 What you have to do will decide if you are going to use static or not, as long as you keep your program clean and easy to maintain.只要您保持程序干净且易于维护,您必须做的将决定是否要使用静态。

Easily speaking, and not in the language of the elders, static stands for something that don't belong to any instance of this class but has an effect on them.简单地说,不是用长辈的语言,静态代表不属于这个类的任何实例但对它们有影响的东西。 An example of a static property in a class that generates instances is for example a factor, which should be global for all instances of the class, to take part in a calculation that is done inside instances.生成实例的类中的静态属性的一个示例是例如一个因子,该因子对于该类的所有实例应该是全局的,以参与在实例内部完成的计算。 To this case, and to my opinion, it is better to have this factor declared as static rather that have it in every single instance.对于这种情况,我认为,最好将此因素声明为静态,而不是在每个实例中都包含它。 Especially if this factor changes in the lifetime of your program to affect the next calculation.特别是如果这个因素在程序的生命周期中发生变化以影响下一次计算。

You need to ask a question to youself: why I need x to be static?你需要问自己一个问题:为什么我需要 x 是静态的?

If you make x static it means that x is a part of all objects of class A, but when x is not static it means, than x is a part only of one object.如果将 x 设为静态,则表示 x 是 A 类所有对象的一部分,但是当 x 不是静态时,则意味着 x 仅是一个对象的一部分。

In geleral using of static fields is painfull for bug tracking, but in some cases this is very helpfull.在一般情况下,静态字段的使用对于错误跟踪来说是痛苦的,但在某些情况下这非常有帮助。

I suggest you to look in using of singelton http://en.wikipedia.org/wiki/Singleton我建议您查看使用单项http://en.wikipedia.org/wiki/Singleton

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

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