如果这是重复,请原谅; 我很确定以前会问这个问题,我看了一下,但没有找到傻瓜.
我可以在C#中创建一个静态局部变量吗?如果是这样,怎么样?
我有一个很少使用的静态私有方法.静态方法使用正则表达式,我想初始化一次,并且仅在必要时.
在C中,我可以使用本地静态变量来完成此操作.我可以用C#做这个吗?
当我尝试编译此代码时:
private static string AppendCopyToFileName(string f)
{
static System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");
}
Run Code Online (Sandbox Code Playgroud)
......它给了我一个错误:
错误CS0106:修饰符'static'对此项无效
如果没有本地静态变量,我想我可以通过创建一个小的新私有静态类来近似我想要的,并将方法和变量(字段)插入到类中.像这样:
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);
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
考虑到这一点,使用这样的帮助程序类可以在效率上产生更大的净节省,因为除非必要,否则Helper类不会被JIT或加载.对?
Hen*_*man 11
不,C#不支持此功能.你可以接近:
private static System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");
private static string AppendCopyToFileName(string f)
{
}
Run Code Online (Sandbox Code Playgroud)
这里唯一的区别是're'的可见性.它不仅仅暴露于该方法.
该re变量将被初始化的第一次包含类以某种方式使用.所以把它放在一个专门的小班上.
C# 不支持静态局部变量。除了上面发布的内容之外,这里还有 2004 年关于该主题的 MSDN 博客文章:Why does C# not support static method variables?
(微软自己的存档中的相同博客条目。网络存档保留了评论。微软存档没有。)
不在 C# 中,仅在 Visual Basic .NET 中:
Sub DoSomething()
Static obj As Object
If obj Is Nothing Then obj = New Object
Console.WriteLine(obj.ToString())
End Sub
Run Code Online (Sandbox Code Playgroud)
VB.NET 有很多 C# 没有的好东西,这就是我选择 VB.NET 的原因。
小智 5
很不幸的是,不行.我真的很喜欢这种可能性.
我知道你能做什么.
创建一个类,该类将提供对特定于实例的值的访问,这些值将静态保留.
像这样的东西:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
可以这样使用......
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这不是一个完美的解决方案,而是一个有趣的玩具.
每个Namespace.Class.Method范围只能有一个这种类型的静态变量.将无法在属性方法中工作 - 它们都解析为相同的名称 - get_InstanceId.
为什么不在static readonly类上创建成员并在静态构造函数中初始化它呢?
这将为您带来相同的性能优势 - 它只会初始化一次.
| 归档时间: |
|
| 查看次数: |
17699 次 |
| 最近记录: |