与
请原谅,如果这是一个副本;我很确定这是以前问过的,我看了一下,但没有找到一个副本。
我可以在C#中创建一个静态局部变量吗?如果是这样的话,是怎么做的?
我有一个很少使用的静态私有方法。静态方法使用一个正则表达式,我只想初始化一次,而且只在必要时初始化。
在C语言中,我可以用一个局部静态变量来做这件事。我能在C#中做到这一点吗?
当我尝试编译这段代码时:
private static string AppendCopyToFileName(string f)
{
static System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");
}
...it给了我一个错误:
静态错误:修饰符‘
’对该项无效
如果没有局部静态变量,我想我可以通过创建一个小型的新私有静态类,并将方法和变量(字段)插入到类中,来接近我想要的。如下所示:
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类将在效率上产生更大的净节省,因为除非必要,否则Helper类将不会被JIT或加载。对吗?
发布于 2010-03-07 00:41:44
不,C#不支持此功能。您可以使用以下命令:
private static System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");
private static string AppendCopyToFileName(string f)
{
}
这里唯一的区别是're‘的可见性。它不仅向方法公开,还向类公开。
第一次以某种方式使用包含类时,将初始化re
变量。所以把这个放在一个专门的小班级里。
发布于 2016-04-25 18:25:03
不是在C#中,仅在Visual Basic .NET中:
Sub DoSomething()
Static obj As Object
If obj Is Nothing Then obj = New Object
Console.WriteLine(obj.ToString())
End Sub
VB.NET有很多C#没有的好东西,这就是我选择VB.NET的原因。
发布于 2010-03-07 00:22:20
很遗憾,我不会。我真的很喜欢C语言中的这种可能性。
我知道你能做什么。
创建一个类,该类将提供对特定于实例的值的访问,这些值将被静态保留。
如下所示:
class MyStaticInt
{
// Static storage
private static Dictionary <string, int> staticData =
new Dictionary <string, int> ();
private string InstanceId
{
get
{
StackTrace st = new StackTrace ();
StackFrame sf = st.GetFrame (2);
MethodBase mb = sf.GetMethod ();
return mb.DeclaringType.ToString () + "." + mb.Name;
}
}
public int StaticValue
{
get { return staticData[InstanceId]; }
set { staticData[InstanceId] = value; }
}
public MyStaticInt (int initializationValue)
{
if (!staticData.ContainsKey (InstanceId))
staticData.Add (InstanceId, initializationValue);
}
}
可以这样使用...
class Program
{
static void Main (string[] args)
{
// Only one static variable is possible per Namespace.Class.Method scope
MyStaticInt localStaticInt = new MyStaticInt (0);
// Working with it
localStaticInt.StaticValue = 5;
int test = localStaticInt.StaticValue;
}
}
这不是一个完美的解决方案,但却是一个有趣的玩具。
每个Namespace.Class.Method作用域只能有一个此类型的静态变量。在属性方法中不起作用-它们都解析为相同的名称- get_InstanceId。
https://stackoverflow.com/questions/2393156
复制相似问题