简体   繁体   English

什么时候不要在 C# 中使用 static 关键字?

[英]When not to use static keyword in C#?

What makes it a poor practice to use static keyword when defining a method in C#?在 C# 中定义方法时使用 static 关键字的不良做法是什么? I know that with static we can reach directly to the function in the class without creating an instance of the class.我知道使用static我们可以直接访问类中的函数而无需创建类的实例。 But when we shouldn't use static?但是什么时候我们不应该使用静态呢?

There is a complete explanation for the use of the 'static' property here by Microsoft.微软在这里对“静态”属性的使用有完整的解释。

In a web framework's experience (.NET Core for this) for instance, we use static declaration for primitive values that WILL NOT require any change.例如,在 Web 框架的经验中(针对此的 .NET Core),我们对不需要任何更改的原始值使用静态声明。

A method that does not access any instance data should actually be marked as static : https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1822-mark-members-as-static?view=vs-2017 It might still be declared as a private method depending on the usage.不访问任何实例数据的方法实际上应该标记为statichttps : //docs.microsoft.com/en-us/visualstudio/code-quality/ca1822-mark-members-as-static?view=vs- 2017它可能仍被声明为private方法,具体取决于用法。

If the method does access any instance data it cannot be static.如果该方法确实访问了任何实例数据,则它不能是静态的。 The compiler enforces this.编译器强制执行此操作。

Common examples of static methods are for example String.Format and Int32.Parse .静态方法的常见示例是例如String.FormatInt32.Parse It makes no sense to allocate a string or an int before calling these methods.在调用这些方法之前分配stringint是没有意义的。

You create a static method when you don' t need the method to access any of the non-static elements on your class.当您不需要该方法来访问您的类中的任何非静态元素时,您可以创建一个静态方法。 For example take in account DateTime.Parse method.例如考虑DateTime.Parse方法。 You can create an instance of DateTime as usual but if you need to parse a specific date, you can call DateTime.Parse to return a valid DateTime without creating a DateTime instance per se.您可以像往常一样创建DateTime的实例,但如果您需要解析特定日期,则可以调用DateTime.Parse以返回有效的 DateTime,而无需创建DateTime实例本身。 As that method does not access any specific element of DateTime class, it is declared as static由于该方法不访问 DateTime 类的任何特定元素,因此它被声明为static

More info:更多信息:

https://www.codeproject.com/Questions/1208992/When-to-use-static-methods-Csharp https://www.codeproject.com/Questions/1208992/When-to-use-static-methods-Csharp

https://hackernoon.com/c-static-vs-instance-classes-and-methods-50fe8987b231 https://hackernoon.com/c-static-vs-instance-classes-and-methods-50fe8987b231

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

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