决定将 C# 类设为静态

发布于 2024-12-08 12:58:08 字数 260 浏览 3 评论 0原文

如果我有一个 C# 中的 Utilities.cs 类,其中仅包含静态方法,

例如

public static string DoSomething()
{
    return "something";
}

我应该使类本身静态吗?

public static Utilities()
{
    ...

使类静态有什么好处吗?

If I have a Utilities.cs class in C#, which contains only static methods

e.g.

public static string DoSomething()
{
    return "something";
}

Should I make the class itself static?

public static Utilities()
{
    ...

Does making the class static have any advantages?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

肩上的翅膀 2024-12-15 12:58:09

是的,你应该。它可以阻止人们在不应该实例化该类的情况下实例化该类,并使该类的目的更加清晰。请阅读MSDN 页面以获取更多信息

如果要添加扩展方法

您应该仔细考虑实用程序类。想想这些方法是否真正属于那里,或者是否有一种更面向对象的方式来实现它。

另请查看这个问题以及 Jon Skeet 的回答。< /em>

Yes you should. It stops people from instantiating the class when they shouldn't, and makes the purpose of the class clearer. Have a read of the MSDN page for more information.

You also need to mark the class as static if you want to add Extension Methods

You should think carefully about utility classes. Think whether the methods truly belong there, or if there's a more OO way of doing it.

Also look at this question and the answer by Jon Skeet.

檐上三寸雪 2024-12-15 12:58:09

主要优点是它使您的设计意图更加清晰,并强制执行这些意图。例如,您不能从静态类继承(即专门化它),也不能创建它的实例(它实际上是单例)。这些都是您的实用程序类的设计意图。

但是,应谨慎使用静态类和方法,因为它使得改变程序的行为变得困难。静态类和方法非常具体,不能(轻易)被替换,就像使用接口和构造函数注入时的情况一样。然而,静态类和成员可能很有用,但很少。过度使用静态会降低软件的灵活性,并且更难以测试。

The main advantage is that it makes your design intent clearer, and enforces those intents. For instance you cannot inherit from a static class (i.e. specialize it), and you cannot make an instance of it (it is in effect a singleton). These would both be design intents of your utilities class.

However, static classes and methods should be used with caution, as it makes it difficult to vary behaviour of your program. Static classes and methods are very concrete and cannot be (easily) substituted, as would be the case if you used interfaces and constructor injection. Static classes and members can however be useful, but rarely. Overuse of statics make your software less flexible, and more difficult to test.

花桑 2024-12-15 12:58:09

是的,你应该将其设为静态。使其静态可防止其被实例化。它的主要目的是告诉使用该类的人它只包含静态方法,这有助于提高可读性。

Yes, you should make it static. Making it static prevents it from being instanced. It's primarily designed to tell the person using the class that it only contains static methods, which helps readability.

偏闹i 2024-12-15 12:58:09

只有静态类不能包含非静态成员,这样可以防止您意外添加它们。另外,正如 Ray 的回答中提到的,它会让你的代码更清晰。

Only that static class can not contain non-static members, so preventing you from accidentally adding them. Also as mentioned in Ray's answer, it will make your code clearer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文