为什么 C# 不像 C 那样支持局部静态变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1049689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:59:55  来源:igfitidea点击:

Why doesn't C# support local static variables like C does?

c#static

提问by JoelFan

Why doesn't C# have local static variables like C? I miss that!!

为什么 C# 没有像 C 那样的局部静态变量?我想念那个!!

采纳答案by Sanu Uthaiah Bollera

You can simulate it using a delegate... Here is my sample code:

您可以使用委托模拟它......这是我的示例代码:

public Func<int> Increment()
{
    int num = 0;
    return new Func<int>(() =>
    {
        return num++;
    });
}

You can call it like this:

你可以这样称呼它:

 Func<int> inc = Increment();
 inc();

回答by LBushkin

C# is a component-oriented language and doesn't have the concept of variables outside the scope of a class or local method. Variables within a method cannot be declared static either, as you may be accustomed to doing in C. However, you can always use a class static variable as a substitute.

C# 是一种面向组件的语言,没有类或本地方法范围之外的变量概念。方法中的变量也不能声明为静态变量,就像您在 C 中习惯做的那样。但是,您始终可以使用类静态变量作为替代。

As a general practice, there are usually ways to solve programming problems in C# without resorting to using method-level statics. State is generally something you should design into classes and types, not methods.

作为一般做法,通常有一些方法可以解决 C# 中的编程问题,而无需使用方法级静态。状态通常是您应该设计到类和类型中的东西,而不是方法。

回答by Jon Skeet

State is generally part of an objector part of a type, not part of a method. (The exception being captured variables, of course.)

状态通常是对象的一部分或类型的一部分,而不是方法的一部分。(当然,捕获的变量是例外。)

If you want the equivalent of a local static variable, either create an instance variable or a static variable - and consider whether the method itself should actually be part of a different type with that state.

如果你想要一个局部静态变量的等价物,要么创建一个实例变量,要么创建一个静态变量 - 并考虑方法本身是否应该实际上是具有该状态的不同类型的一部分。

回答by Timothy Carter

I'm not nearly as familiar with C as I am C#, but I believe you can accomplish everything you could with a local static, by using a class level static that is only used for one method. Obviously, this comes with some syntactic change, but I believe you can get whatever functionality you need.

我对 C 的熟悉程度不如我对 C# 的熟悉,但我相信您可以通过使用仅用于一种方法的类级别静态来完成您可以使用本地静态完成的所有工作。显然,这会带来一些语法变化,但我相信您可以获得所需的任何功能。

Additionally, Eric Lippert answers questions like this on his bloga lot. Generally answered in this way: "I am asked "why doesn't C# implement feature X?" all the time. The answer is always the same: because no one ever designed, specified, implemented, tested, documented and shipped that feature." Essentially his answers generally boil down to, it costs money to add any feature, and therefore, many potential features are not implemented because they have not come out on the positive side of the cost benefit analysis.

此外,Eric Lippert 在他的博客上经常回答这样的问题。通常以这种方式回答:“我一直被问到“为什么 C# 不实现功能 X?”。答案总是一样的:因为没有人设计、指定、实现、测试、记录和发布该功能。 ” 从本质上讲,他的回答通常归结为,添加任何功能都需要花钱,因此,许多潜在的功能没有实现,因为它们没有出现在成本效益分析的积极方面。

回答by mike

I think the idea of local statics is just as easily solved by creating public static fields to the class. Very little logical change don't you think?

我认为通过为类创建公共静态字段可以轻松解决本地静态的想法。很少有逻辑变化,你不觉得吗?

If you think it would be a big logical change, I'd be interested to hear how.

如果你认为这将是一个很大的逻辑变化,我很想听听如何。

class MyClass
{
    public static float MaxDepthInches = 3;

    private void PickNose()
    {
        if (CurrentFingerDepth < MyClass.MaxDepthInches)
        {
            CurrentFingerDepth++;
        }
    }
}

回答by user313888

Because they screwed up, and left out a useful feature to suit themselves.

因为他们搞砸了,遗漏了一个适合自己的有用功能。

All the arguments about how you should code, and what's smart, and you should reconsider your way of life, are pompous defensive excuses.

所有关于你应该如何编码、什么是聪明的、你应该重新考虑你的生活方式的争论,都是自负的辩护借口。

Sure, C# is pure, and whatchamacallit-oriented. That's why they auto-generate persistent locals for lambda functions. It's all so complicated. I feel so dumb.

当然,C# 是纯粹的,并且面向什么。这就是为什么他们为 lambda 函数自动生成持久局部变量。一切都是那么复杂。我觉得好傻

Loop scope static is useful and important in many cases.

循环范围静态在许多情况下是有用且重要的。

Short, real answer, is you have to move local statics into class scope and live with class namespace pollution in C#. Take your complaint to city hall.

简短而真实的答案是,您必须将本地静态变量移动到类范围内,并忍受 C# 中的类命名空间污染。向市政厅投诉。

回答by Nick Alexeev

The MSDN blog entry Why doesn't C# support static method variables?deals with the exact question asked in the original post:

MSDN 博客条目为什么 C# 不支持静态方法变量?处理原始帖子中提出的确切问题:

There are two reasons C# doesn't have this feature.

First, it is possible to get nearly the same effect by having a class-level static, and adding method statics would require increased complexity.

Second, method level statics are somewhat notorious for causing problems when code is called repeatedly or from multiple threads, and since the definitions are in the methods, it's harder to find the definitions.

[Author: Eric Gunnerson]

C# 没有此功能有两个原因。

首先,通过类级静态可以获得几乎相同的效果,并且添加方法静态需要增加复杂性。

其次,当代码被重复调用或从多个线程调用时,方法级别的静态会导致问题而臭名昭著,并且由于定义在方法中,因此很难找到定义。

[作者:埃里克·冈纳森]

回答by Newell

Logically, yes. It would be the same as a class-level static member that was only used in that one method. However, a method-level static member would be more encapsulated. If the data stored in a member is only meant to be used by a single method, it should only be accessible by that single method.

从逻辑上讲,是的。它与仅在该方法中使用的类级别静态成员相同。但是,方法级别的静态成员会被更多地封装。如果存储在成员中的数据只能由单个方法使用,则它应该只能由该单个方法访问。

However, you CAN achieve almost exactly the same effect in C# by creating a nested class.

但是,您可以通过创建嵌套类在 C# 中实现几乎完全相同的效果。

回答by Lee Louviere

Because static local variables are tied to the method, and the method is shared amongst all instances.

因为静态局部变量与该方法相关联,并且该方法在所有实例之间共享。

I've had to correct myself and other programmers who expect it to be unique per class instance using the method.

我不得不纠正自己和其他程序员,他们希望使用该方法的每个类实例都是唯一的。

However, if you make it a static class, or static instance of a class, it's syntactically clear whether there's an instance per container-class, or one instance at all.

但是,如果您将其设为静态类或类的静态实例,则在语法上很清楚是每个容器类都有一个实例,还是根本没有一个实例。

If you don't use these, it becomes easier to refactor later as well.

如果你不使用这些,以后重构也会变得更容易。

回答by fostandy

If you can imagine some sort of Lippert/Farnsworth hybrid entity announcing GOOD NEWS EVERYONE!, C# 6.0 allows the using staticstatement. This effectively allows you to import static class methods (and, it seems, properties and members as well) into the global scope.

如果您能想象某种 Lippert/Farnsworth 混合实体向所有人宣布好消息!, C# 6.0 允许using static声明。这有效地允许您将静态类方法(似乎还有属性和成员)导入全局范围。

In short, you can do something like this:

简而言之,您可以执行以下操作:

using NUnit.Framework;
using static Fizz.Buzz;

class Program
{
    [Test]
    public void Main()
    {
        Method();
        int z = Z;
        object y = Y;
        Y = new object();
    }
}


namespace Fizz
{
    class Buzz
    {
        public static void Method()
        {
        }

        public static int Z;

        public static object Y { get; set; }
    }
}   

While this is only available in C# 6.0, from what I understand the generated assemblies should be compatible with previous .NET platforms (correct me if I'm wrong).

虽然这仅在 C# 6.0 中可用,但据我所知,生成的程序集应该与以前的 .NET 平台兼容(如果我错了,请纠正我)。