请问C#支持使用静态局部变量的? [英] Does C# support the use of static local variables?
问题描述
赦免如果这是一个重复;我敢肯定,这将先前已经问过了,我看了,但没有找到一个傻瓜。
Pardon if this is a duplicate; I was pretty sure this would have been asked previously, and I looked but didn't find a dupe.
是否有可能对我来说,C#创建静态局部变量?如果是这样,怎么样?
Is it possible for me to create a static local variable in C#? If so, how?
我有一个很少使用的静态私有方法。静态方法使用正则表达式,我想初始化的一次的,并且只在必要时。
I have a static private method that is used rarely. the static method uses a Regular Expression, which I would like to initialize once, and only when necessary.
在C,我可以与当地的静态变量做到这一点。我能做到这一点在C#中?
In C, I could do this with a local static variable. Can I do this in C#?
当我尝试编译这段代码:
When I try to compile this code:
private static string AppendCopyToFileName(string f)
{
static System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");
}
...它给了我一个错误:
...it gives me an error:
错误CS0106:修改器静态是无效的此项目
error CS0106: The modifier 'static' is not valid for this item
如果没有局部静态变量,我想我可以接近我想要的东西通过创建一个很小的新的私人静态类,并插入了两种方法和变量(场)进入类。像这样的:
If there's no local static variable, I suppose I could approximate what I want by creating a tiny new private static class, and inserting both the method and the variable (field) into the class. Like this:
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'd或装载,除非必要的。对吧?
Thinking about this more, using a helper class like this there would yield a bigger net savings in efficiency, because the Helper class would not be JIT'd or loaded unless necessary. Right?
推荐答案
没有,C#不支持这一点。
No, C# does not support this. You can come close with:
static System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");
private static string AppendCopyToFileName(string f)
{
}
这里唯一的不同是重的知名度。我不认为C或Java的行为有什么不同的问候时,这个被初始化为。
The only difference here is the visibility of 're'. I don't think C or Java will behave any different with regards to when this is initialized.
这篇关于请问C#支持使用静态局部变量的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!