制作方法:所有静态类中 [英] Making Methods All Static in Class

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

问题描述

我是基于我的班级我的一个同事告诉(它是一个实例类),如果你有任何字段在你的类(支持字段),只要在类的静态所有方法,或者使课堂单身这样你就不必使用new关键字调用这个BL类的方法。

I was told by my colleague based on one of my classes (it is an instance class) that if you have no fields in your class (backing fields), just make all methods static in the class or make the class a singleton so that you don't have to use the keyword new for calling methods in this BL class.

我想这是常见的,好的做法呢?基本OOP?我只是想看看人们对这种看法。

I assume this is common and good practice? Basic OOP? I just want to see people's opinion on that.

我觉得基本上他的说法,因为没有国家,没有必要方法是实例方法。

I think basically he's saying since there's no state, no need for the methods to be instance methods.

我不知道每次使其成为单身作为一个选项在这种情况下......是某种图案或好的建议他给我吗?

I'm not sure about making it a singleton every time as an option in this case...is that some sort of pattern or good advice he's giving me?

下面是我在谈论的类(请不要转贴此代码的任何在这个线程,这是私人的):的 http://www.elbalazo.net/post/class.txt

Here's the class I'm talking about (please do not repost any of this code in this thread, this is private): http://www.elbalazo.net/post/class.txt

推荐答案

很少有缺点调用new,建设类引用,特别是如果类没有状态。分配是快.NET,所以我不会用这个作为单独的理由一类是静态的。

There is very little downside to calling new and constructing a class reference, especially if the class has no state. Allocations are fast in .NET, so I wouldn't use this alone as a justification for a class to be static.

通常情况下,我觉得一个类应静如果该类没有具体的语境 - 如果你正在使用类只是作为一个实用的方法还是非上下文具体操作的占位符,然后是有意义的是一个静态类

Typically, I feel a class should be made static if the class has no specific context - if you're using the class just as a placeholder for "utility" methods or non-context specific operations, then it makes sense to be a static class.

如果这类具有上下文特定需要,以及在一个具体的意义上的含义,那么它可能并不能证明是静态的,即使它没有状态(尽管这是罕见的)。有其中类的目的是通过它的引用本身,它提供了一种无需任何局部变量(引用本身)的状态定义的时间。

If that class has a specific need for context, and a meaning in a concrete sense, then it probably does not justify being static, even if it has no state (although this is rare). There are times where the class purpose is defined by its reference itself, which provides "state" of a sort (the reference itself) without any local variables.

话虽这么说,有一个静态类和一个单间有很大的区别。单身是一种不同的动物 - 你想,当你需要一个实例来使用它,但是,只有类的一个实例被创建。有状态的单身,但你使用这个模式来强制执行,只有国家的一个副本。这有一个非常不同的含义,我会强烈建议使用单只是为了以防需要以召唤新的避免。

That being said, there is a big difference between a static class and a singleton. A singleton is a different animal - you want to use it when you need an instance, but only one instance, of the class to be created. There is state in a singleton, but you are using this pattern to enforce that there is only a single copy of the state. This has a very different meaning, and I would highly recommend avoiding using a singleton just to prevent needing to "call new".

这篇关于制作方法:所有静态类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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