方法的静态变量'初始化一次(不包装在自己的类中)
本文关键字:一次 包装 自己的 变量 静态 初始化 方法 | 更新日期: 2023-09-27 18:08:41
我试图定义一个方法,有一些变量" I ",这样:
- 分配和初始化"i"的代码只调用一次(想象一个巨大的数组)
- "i"在连续执行方法时保持其值
- "i"只在方法内部可见。
这类似于c++的静态变量。
在Scala中我可以这样做:
val func = {
println("allocating")
var i = 0
() => {
i += 1
i
}
}
func()
func()
func()
我会得到:
allocating
1
2
3
现在,在c#中:
试题:
Func<int> func = (
(Func<Func<int>>)( () => {
Console.WriteLine("allocating");
int i = 1;
return ((Func<int>)(() => i++));
}
)
)();
Console.WriteLine (func ());
Console.WriteLine (func ());
Console.WriteLine (func ());
但是,这是非常丑陋的。
是否有更好的标准方法来实现我想要的?
编辑:许多人发布了将方法包装在类中的代码。这不是我想要的,我想要在任何类中都有这些方法,而不是将它们包装在自己的类中。这就是为什么,在我发布的代码中,我将我想要的函数包装在另一个函数中,该函数在分配/初始化一些变量后返回它。
c#不支持函数的局部静态变量
你的描述是一个静态成员,只有一个方法可以看到。
你应该考虑:
- 将类静态成员封装在类中的函数中
例子:
class MyType
{
static int[] myArray = { 1, 2, 3, 4 };
void foo()
{
myArray[i] = ... // foo is the only method of MyType, hence the only to have ccess
}
}
- 创建封装变量 的Type的静态实例
例子:
public class Test2
{
int[] myArray = { 1, 2, 3, 4 };
}
public class MyClass
{
static Test2 instance; // Only methods of MyClass` will have access to this static instance
void foo()
{
instance.myArray[i] = ...
}
}
您可以通过实现您的"静态"行为来设计事物的行为方式…
public class c1
{
private static int i = 0; // You might not want it static, look comment after the code
public int alocating_method() //could be protected
{
Console.WriteLine("allocating");
return ++i;
}
}
public class c2 : c1
{
static void Main(string[] args)
{
c2 p = new c2();
Console.WriteLine(p.alocating_method());
Console.WriteLine(p.alocating_method());
}
}
在c2中,您只能通过alocating_method…
使用变量i如果您希望c2的每个实例都有自己的变量i(我认为您可能会这样做),请删除静态修饰符…