决定做一个C#类的静态 [英] Deciding to make a C# class static

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

问题描述

如果我在C#中的 Utilities.cs 类,其中只包含静态方法

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

例如

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



我应该做的类本身静态的?

Should I make the class itself static?

public static Utilities()
{
    ...

是否使类的静态有什么优势?

Does making the class static have any advantages?

推荐答案

是的,你应该。它停止从实例化类时,他们不应该的人,使得该类更加清晰的目的。有 MSDN的页面了解更多信息

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.

这篇关于决定做一个C#类的静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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