简体   繁体   English

静态类的静态方法与非静态类的静态方法(C#)

[英]Static Method of a Static Class vs. Static Method of a Non-Static Class ( C# )

I was asked the above question in an interview. 我在接受采访时被问到了上述问题。 Could you please explain the differences? 你能解释一下这些差异吗? ( performance - memory - usage - when to use which ? ) (性能 - 内存 - 使用 - 何时使用哪个?)

Thank you, 谢谢,

Erkan 二崁

Declaring a static class documents your intent for that class to be a collection of static functionality, and anyone adding instance members will get a compilation error. 声明一个静态类会将您对该类的意图记录为静态功能的集合,任何添加实例成员的人都会收到编译错误。

A non-static class with static members usually indicates that the class is designed to be instantiated at some point. 具有静态成员的非静态类通常表示该类被设计为在某个时刻被实例化。 Static methods of these classes usually do one of two things: 这些类的静态方法通常执行以下两种操作之一:

  1. Provide a factory method for creating an instance of that type; 提供用于创建该类型实例的工厂方法;
  2. Provide helper functionality that does not require an instance of the type; 提供不需要该类型实例的帮助程序功能;

Also, as mentioned already, extension methods can only be declared on a static class. 此外,如前所述,扩展方法只能在静态类上声明。

I assume you were asked for the differences? 我假设你被问到了这些差异?

A static method on a static class can be used to define an extension method. 静态类上的静态方法可用于定义扩展方法。 A static method on a non-static class cannot. 非静态类上的静态方法不能。

In terms of performance and memory usage; 在性能和内存使用方面; precisely nothing. 没什么。 Having a static class means you know there are no instances, but back in 1.1 having a private constructor sufficed. 拥有一个静态类意味着你知道没有实例,但是在1.1中有一个私有构造函数就足够了。 Use a static class if it simply makes no sense to have an instance! 如果只有一个实例没有意义,请使用静态类! (utility classes etc) (实用班等)

When you are providing utility functions and all your methods are static, I recommend you use static methods in a static class. 当您提供实用程序函数并且所有方法都是静态的时,我建议您在静态类中使用静态方法。

When you want to provide utility methods that just deal with your instance, I recommend you use static methods in a non-static class. 如果要提供仅处理实例的实用程序方法,我建议您在非静态类中使用静态方法。 For example: 例如:

var myClass = MyClass.Create();
var myClass = MyClass.Parse("serialized.MyClass");

One major difference I faced when deciding whether to go with normal class with all static methods or, use a static class, is that a normal class supports interface implementation, where as static class does not. 在决定是否使用所有静态方法的普通类时,或者使用静态类时,我遇到的一个主要区别是普通类支持接口实现,而静态类则不支持。 I use static class only when I am sure it will be a collection of static functions (usually helper functions), and will never be in the main stream of program. 我只在确定它是静态函数的集合(通常是辅助函数)时才使用静态类,并且永远不会出现在程序的主流中。 I promote interface programming, for dependency injections, unit testing etc. So, for main flow of program, I use normal class with static methods. 我推动接口编程,依赖注入,单元测试等。因此,对于程序的主流程,我使用普通类和静态方法。

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

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