何时在 C# 中使用静态类 [英] When to use static classes in C#

查看:32
本文介绍了何时在 C# 中使用静态类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是 MSDN 不得不说何时使用静态类:

<块引用>

静态类 CompanyInfo{public static string GetCompanyName() { return "CompanyName";}公共静态字符串 GetCompanyAddress() { return "CompanyAddress";}//...}

以静态类为单位组织方法不与特定对象相关联.此外,静态类可以使您实施更简单、更快因为您不必创建对象来调用它的方法.组织方法很有用以一种有意义的方式在课堂上,比如 Math 类的方法在系统命名空间中.

对我来说,该示例似乎并未涵盖静态类的许多可能使用场景.过去,我将静态类用于相关函数的无状态套件,但仅此而已.那么,在什么情况下应该(也不应该)将类声明为静态?

解决方案

我在早期的 Stack Overflow 回答中写了我对静态类的想法:使用单一方法类——最佳方法?em>

我曾经喜欢充满静态方法的实用程序类.他们对辅助方法进行了很好的整合,否则会导致冗余和维护地狱.它们非常易于使用,无需实例化,无需处理,只需触发'n'forget.我想这是我第一次在不知情的情况下尝试创建面向服务的架构——许多无状态服务只是完成了他们的工作,没有别的.然而,随着系统的发展,龙即将到来.

多态

假设我们有方法 UtilityClass.SomeMethod ,它很高兴地嗡嗡作响.突然间,我们需要稍微改变一下功能.大多数功能是相同的,但我们必须更改几个部分.如果它不是静态方法,我们可以创建一个派生类并根据需要更改方法内容.由于它是静态方法,我们不能.当然,如果我们只需要在旧方法之前或之后添加功能,我们可以创建一个新类并在其中调用旧的 - 但这太糟糕了.

界面问题

由于逻辑原因,不能通过接口定义静态方法.因为我们不能覆盖静态方法,所以当我们需要通过它们的接口传递静态类时,静态类是无用的.这使我们无法将静态类用作策略模式的一部分.我们可能会通过传递委托而不是接口来修补一些问题.

测试

这基本上与上面提到的界面问题密切相关.由于我们交换实现的能力非常有限,我们也很难用测试代码替换生产代码.同样,我们可以将它们包装起来,但这需要我们更改大部分代码,以便能够接受包装器而不是实际对象.

培养斑点

由于静态方法通常用作实用方法,而实用方法通常有不同的用途,我们很快就会得到一个充满非连贯功能的大类——理想情况下,每个类在系统.只要课程的目的明确,我宁愿有五倍的课程.

参数蠕变

首先,这个可爱而天真的静态方法可能只需要一个参数.随着功能的增长,添加了几个新参数.很快就会添加更多可选的参数,因此我们创建方法的重载(或仅添加默认值,在支持它们的语言中).不久,我们就有了一个接受 10 个参数的方法.只有前三个是真正需要的,参数 4-7 是可选的.但是如果指定了参数6,7-9也需要填写...如果我们创建一个类的目的是做这个静态方法所做的单一目的,我们可以通过在构造函数,并允许用户通过属性设置可选值,或同时设置多个相互依赖的值的方法.此外,如果一个方法已经发展到这种程度的复杂性,它很可能无论如何都需要在自己的类中.

要求消费者无故创建类的实例

最常见的论点之一是:为什么要求我们类的使用者创建一个实例来调用这个单一方法,而之后却不再使用该实例?在大多数语言中,创建一个类的实例是一个非常便宜的操作,所以速度不是问题.为消费者添加额外的一行代码是一种低成本,可为未来更易于维护的解决方案奠定基础.最后,如果您想避免创建实例,只需为您的类创建一个单例包装器,以便轻松重用——尽管这确实要求您的类是无状态的.如果它不是无状态的,您仍然可以创建处理所有内容的静态包装方法,同时从长远来看仍然为您提供所有好处.最后,您还可以创建一个隐藏实例化的类,就好像它是一个单例一样:MyWrapper.Instance 是一个只返回 new MyClass();

的属性

只有西斯才能处理绝对值

当然,我不喜欢静态方法也有例外.不会造成任何膨胀风险的真正实用程序类是静态方法的极好案例 - 以 System.Convert 为例.如果您的项目是一次性的,不需要未来的维护,那么整体架构真的不是很重要 - 静态或非静态,并不重要 - 但是开发速度很重要.

标准、标准、标准!

使用实例方法并不妨碍您也使用静态方法,反之亦然.只要差异化背后有理由,而且是标准化的.没有什么比查看具有不同实现方法的业务层更糟糕的了.

Here's what MSDN has to say under When to Use Static Classes:

static class CompanyInfo
{
    public static string GetCompanyName() { return "CompanyName"; }
    public static string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}

Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.

To me, that example doesn't seem to cover very many possible usage scenarios for static classes. In the past I've used static classes for stateless suites of related functions, but that's about it. So, under what circumstances should (and shouldn't) a class be declared static?

解决方案

I wrote my thoughts of static classes in an earlier Stack Overflow answer: Class with single method -- best approach?

I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service-oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.

Polymorphism

Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.

Interface woes

Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by passing delegates instead of interfaces.

Testing

This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up, but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.

Fosters blobs

As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.

Parameter creep

To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyway.

Demanding consumers to create an instance of classes for no reason

One of the most common arguments is: Why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns new MyClass();

Only a Sith deals in absolutes

Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.

Standards, standards, standards!

Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.

这篇关于何时在 C# 中使用静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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