gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:04:50 25 4
gpt4 key购买 nike

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

例如:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com