c# - 低级差异 : non-static class with static method vs. 静态类与静态方法

标签 c# .net performance static-classes

我想知道使用具有静态方法的非静态类与具有相同静态方法的静态类的一般好处(或缺点)是什么,除了我不能使用非静态类中的静态方法作为扩展方法。

例如:

class NonStaticClass
{
    public static string GetData()
    {
        return "This was invoked from a non-static class.";
    }
}

与此相比:

static class StaticClass
{
    public static string GetData()
    {
        return "This was invoked from a static class.";
    }
}

使用一种方法优于另一种方法对性能/内存有何影响?

注意:假设我不需要实例化类。我的用例场景仅限于这样的情况:

Console.WriteLine(NonStaticClass.GetData());
Console.WriteLine(StaticClass.GetData());

最佳答案

主要的好处是,如果您将类设为静态,编译器将确保您的类只有静态成员。

因此任何阅读代码的人都会立即看到该类无法实例化,并且没有考虑与该类的任何实例的交互。因为不可能有。

在 clr 级别,没有 static 的概念。静态类既是抽象又是密封,有效地防止了继承和实例化。

至于性能,我看不出编译器或运行时有任何可能对其中一个进行优化。

在这个例子中,我会专注于尽可能清楚地向读者表达您的意图。您以后可以随时进行优化。

关于c# - 低级差异 : non-static class with static method vs. 静态类与静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10033745/

相关文章:

c# - 无法将字符串转换为 DateTIme

c# - Word OpenXML 替换标记文本

c# - 在 C# 中比较两个 List<MyClass>

c++ - 加速从 C++ 文件中读取整数

java - 这两段代码之间有性能差异吗?

c# - JSON 补丁验证 .Net Core

C# TypeConverter.ConvertFrom() 问题

.net - 如何在 Azure Webfarm 中创建分布式共享事务内存?

.net - Microsoft.VisualBasic.Collection 和 .NET System.Collections.Generic.Dictionary(Of TKey, TValue) 之间已知的性能差异是什么?

c# - 面向对象设计