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

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

问题描述

下面就是 MSDN有下的说何时使用静态类


 静态类公司信息
{
    公共静态字符串GetCompanyName(){返回公司名称; }
    公共静态字符串GetCompanyAddress(){返回公司地址; }
    // ...
}

使用一个静态类为单位
  组织方法不
  与特定对象有关。
  同样,静态类可以让你
  实施简单和快速
  因为你没有创建
  为了对象调用它的方法。
  它是组织方法中有用的
  以有意义的方式在类中,
  如数学类的方法
  System命名空间。


对于我来说,这个例子似乎并不涵盖静态类很多种可能的使用场景。在过去,我一直使用的相关功能无国籍套房静态类,但仅此而已。那么,在什么情况下应该(也不应该)一类被声明为static?


解决方案

我写我在前面的堆栈溢出的答案静态类的想法:
类单方法 - 最好的办法

我用爱充满了静态方法的实用工具类。他们提出的辅助方法,否则将位于大约造成冗余和维护地狱很大的整合。他们是非常容易使用,没有实例化,没有处理,只是fire'n'forget。我想这是创造一个面向服务的架构我第一次尝试不知情 - 很多只是做了自己的工作,没有别的无状态的服务。然而,作为一个系统的发展,龙到来。

多态性

说,我们有愉快热闹非凡沿着方法UtilityClass.SomeMethod。突然,我们需要稍微改变功能。大多数的功能是相同的,但我们必须改变几个部分仍然。若不是一个静态方法,我们可以做一个衍生类,并根据需要改变方法的内容。因为它是一个静态方法,我们不能。当然,如果我们只需要前或老方法之后添加的功能,我们可以创建一个新的类并调用旧它里面 - 不过这只是毛

接口困境

静态方法无法通过逻辑原因接口定义。既然我们不能重写静态方法,静态类是没有用的时候,我们需要通过接口来传递他们周围。这使得我们无法使用静态类作为一种战略模式的一部分。我们可能是由<补丁一些问题了href=\"http://blogs.msdn.com/kirillosenkov/archive/2008/02/06/how-to-override-static-methods.aspx\">passing代表,而不是接口。

测试

这基本上是齐头并进与上述接口困境。作为我们实现交换能力是非常有限的,我们也会有麻烦测试code更换生产code。同样,我们可以包装起来,但它会要求我们改变我们的code的大部分只是为了能够接受的包装,而不是实际的对象。

促进斑点

由于静态方法通常被用作实用方法和实用方法通常都会有不同的目的,我们会很快充满了非相干功能的大课堂结束 - 理想情况下,每个类应该有内部的一个单一的目的系统。我宁愿有五次班,只要它们的目的很明确。

参数蠕变

首先,那个小可爱和无辜的静态方法可能需要一个参数。随着功能的增加,一些新的参数被添加。不久,更多的参数被添加是可选的,所以我们创建方法的重载(或者只是添加默认值,以支持他们的语言)。没多久,我们有需要10参数的方法。只有前三个真正需要,参数4-7都是可选的。但是,如果指定的参数6,需要7-9以及...如果我们创建了一个类做这种静态方法做的唯一目的填补,我们可以采取在所需的参数解决这个问题构造,并允许用户通过属性设置可选值,或方法,以同时设置多个相互依赖的值。此外,如果方法已发展到这一数额的复杂性,它极有可能需要在自己的类呢。

要求苛刻的消费者没有理由创建类的实例

其中最常见的论点是:为什么我们班的消费者创造一个实例调用此单个方法,而有没有用事后实例需求呢?创建一个类的实例,在大多数语言中一个非常非常便宜的操作,所以速度不是问题。添加code的一个额外的行对消费者是一种低成本铺设在未来更容易维护解决方案的基础。最后,如​​果你想避免创建实例,只需创建你的类,可以很容易地再利用一个单封装 - 尽管这确实让您的类是无状态的要求。如果不是无状态的,你还可以创建搞定一切静态包装方法,同时还让您从长远来看,所有的好处。最后,你也可以做一个隐藏的实例,就好像它是一个单例类:MyWrapper.Instance是,仅仅返回新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天全站免登陆