代码之家  ›  专栏  ›  技术社区  ›  blez

C中的vb6私有静态

  •  5
  • blez  · 技术社区  · 16 年前

    在VB6中,有一些局部静态变量在过程退出后保留其值。这就像使用公共变量,但是在本地块上。例如:

    sub count()
    static x as integer
    x = x + 1
    end sub
    

    打了10个电话后,x将是10。我试图在.NET(甚至Java)中搜索相同的东西,但没有一个。为什么?它是否在某种程度上打破了OOP模型,并且有没有一种方法来模拟它。

    4 回复  |  直到 10 年前
        1
  •  6
  •   Marc Gravell    16 年前

    最接近的是静态场 外部 方法:

    private static int x;
    public [static] void Foo() {
        x++;
    }
    

    按要求关闭示例:

    using System;
    class Program {
        private static readonly Action incrementCount;
        private static readonly Func<int> getCount;
        static Program() {
            int x = 0;
            incrementCount = () => x++;
            getCount = () => x;
        }
        public void Foo() {
            incrementCount();
            incrementCount();
            Console.WriteLine(getCount());
        }
        static void Main() {
            // show it working from an instance
            new Program().Foo();
        }
    }
    
        2
  •  0
  •   Blindy    16 年前

    为此,可以始终在类中使用静态变量:

    class C
    {
      static int x=0;
    
      void count()
      {
        ++x; // this x gets incremented as you want 
      }
    }
    
        3
  •  0
  •   Daniel Dolz    16 年前

    我记得VisualBasic中的静态私有。他们对某些特定的任务很酷。

    在.NET中没有这样的东西。你将不得不坚持在metod外的静电。

        4
  •  0
  •   Damian Powell    16 年前

    通常,这些类型的变量用于维护迭代器。C是否通过 yield 关键字。下面是一个例子:

    IEnumerable<int> TimesTable(int table)
    {
        for (int i=0 ; i<12 ; i++)
        {
            yield return i * table;
        }
    }
    

    在本例中,我们在n times表中创建值,其中n由调用者指定。我们可以在任何使用迭代器的地方使用它,例如 foreach 循环:

    foreach (var value in TimesTable(3))
    {
        Console.Write(""+ value + " ");
    }
    

    …生产:

    3 6 9 12 15 18 21 24 27 30 33 36  
    

    在C++中,这可能使用了静态变量,比如从VB中描述的那些变量(我不是VB的人,所以我不知道VB语法):

    int TimesTable(int table) {
        static i = 1;
        if (i == 12) {
            i = 1;
        }
        return i++ * table;
    }
    

    C版本优于C++(或VB)等价,因为迭代器可以被提前取消,并且在任何给定的时间都可以有多个迭代器活动。这些事情对于C++版本来说是不正确的,而开发人员不需要做更多的工作。另一方面,它意味着,在C中,像静态变量这样的东西唯一有效的时间是在迭代器实现期间,并且该值不会持续超出该范围。

    我希望这对你有用。

    推荐文章