gpt4 book ai didi

c# - C# 是否支持使用静态局部变量?

转载 作者:IT王子 更新时间:2023-10-29 04:38:25 24 4
gpt4 key购买 nike

Related: How do I create a static local variable in Java?


请原谅这是重复的;我很确定之前会有人问过这个问题,我看了看但没有找到骗子。

我可以在 C# 中创建静态局部变量吗?如果是,怎么办?

我有一个很少使用的静态私有(private)方法。静态方法使用正则表达式,我想对其进行初始化一次,并且仅在必要时进行。

在 C 中,我可以使用局部静态变量来完成此操作。我可以在 C# 中执行此操作吗?

当我尝试编译这段代码时:

    private static string AppendCopyToFileName(string f)
{
static System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");
}

...它给了我一个错误:

error CS0106: The modifier 'static' is not valid for this item


如果没有局部静态变量,我想我可以通过创建一个新的小型私有(private)静态类并将方法和变量(字段)插入到类中来近似我想要的。像这样:

public class MyClass 
{
...
private static class Helper
{
private static readonly System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");

internal static string AppendCopyToFileName(string f)
{
// use re here...
}
}

// example of using the helper
private static void Foo()
{
if (File.Exists(name))
{
// helper gets JIT'd first time through this code
string newName = Helper.AppendCopyToFileName(name);
}
}
...
}

更多地考虑这一点,使用像这样的帮助程序类会在效率上产生更大的净节省,因为除非必要,否则不会对 Helper 类进行 JIT 或加载。对吧?

最佳答案

不,C# 不支持这个。你可以接近:

private static System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");

private static string AppendCopyToFileName(string f)
{

}

此处唯一的区别是“re”的可见性。它不仅暴露给方法,还暴露给类。

re 变量将在第一次以某种方式使用包含类时被初始化。因此,将其保留在专门的小类中。

关于c# - C# 是否支持使用静态局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2393156/

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