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

C中未声明的变量#

c#
  •  5
  • GibboK  · 技术社区  · 14 年前

    是否可以取消声明C#中的变量?如果是,怎么做?

    6 回复  |  直到 14 年前
        1
  •  4
  •   Kharlos Dominguez    14 年前

    在C#(顺便说一下,我想你的意思是取消分配)或任何其他.Net语言中,垃圾收集器不负责取消分配与变量相关的内存。

    对于非托管资源(字体、数据库连接、文件等),您需要显式地调用Dispose方法,或者将变量放置在using块中。

    有关.Net垃圾收集器的详细信息: http://www.csharphelp.com/2006/08/garbage-collection/

        2
  •  10
  •   Nordic Mainframe    14 年前

    关闭包含变量声明的作用域(以“{”引入):

    int c=0;
    {
     int a=1;
     {
      int b=2; 
      c=a+b;
     } // this "undeclares" b
     c=c+a;
    } // this "undeclares" a
    
        3
  •  1
  •   this. __curious_geek    14 年前

    ,您可以在 using Luther 已经提到。

    using (Car myCar = new Car())
    {
        myCar.Run();
    }
    
        4
  •  1
  •   Noldorin    14 年前

    你为什么要明确地这样做呢;背景是什么?最有可能的情况是,您应该简单地使用一个新的变量名,或者将相关的代码部分重构为一个新函数。

        5
  •  0
  •   arneeiri    14 年前

        6
  •  0
  •   Roland Illig    14 年前

    void doSomething(String objectId) {
      BusinessObject obj = findBusinessObject(objectId);
    
      // from this point on the objectId should not be used anymore
      undef objectId;
    
      // continue using obj ...
    }
    

    另一种情况是,当您从接口实现某个方法时,您希望确保不使用其中一个参数,特别是在长方法中。

    Object get(int index, Object defaultValue) {
      undef index, defaultValue;
    
      return "constant default value";
    }
    

    这也可以作为程序员考虑这些未使用的参数的文档。