具有初始化一次的静态变量的方法(不包装在自己的类中)

时间:2014-06-14 13:57:59

标签: c# scala closures

我正在尝试定义一个包含变量“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 ());

然而,这非常难看。

是否有更好的标准方式来实现我想要的目标?

编辑:许多人发布了代码来将方法包装在一个类中。这不是我正在寻找的,我想在任何类中通常使用这些方法而不将它们包装在自己的类中。 这就是为什么,在我发布的代码中,我将我想要的函数包装在另一个函数中,该函数在分配/初始化一些变量之后返回它。

2 个答案:

答案 0 :(得分:0)

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
 }
}
  • 创建封装变量的类型的静态实例

示例:

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] = ...
    }
}

答案 1 :(得分:0)

您可以通过实施&#34;静态&#34;来设计符合您所说方式的内容。行为...

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(我认为你可能会这样做),请删除static修饰符......