内部类和外部类在c#

问题描述:

如何实现在c#内部类和外部类在c#

内外类我有两个嵌套类

class Outer 
{ 
    int TestVariable = 0; 
    class Inner 
    { 
     int InnerTestVariable = TestVariable // Need to access the variable "TestVariable" here 
    } 
} 

其示出错误,而进行编译。

它可以通过

1)制作TestVariable静态

2)传递外类的一个实例,以内部类来解决

但在的java没有必要创建实例或静态的。

我可以在C#中使用相同的功能吗?

+0

可能重复[什么是从嵌套类访问封闭类中的控件的最佳方式?](http://*.com/questions/185124/whats-the-best-way-of-accessing- the-control-in-the-encl-class-from-the-nes) – nawfal 2013-02-25 11:22:48

不,C#在这种情况下与Java没有相同的语义。您可以制作TestVariableconst,static或将Outer的实例传递给Inner的构造函数,如您已经注意到的。

使变量internal或传递给内部的constructor

+0

如果我将该变量声明为内部变量,那么它在内部类中不可访问 – 2010-07-01 08:08:02

您无需甚至有外类实例创建内部类的一个实例,应该在你认为情况会怎么样呢?这就是为什么你不能使用它

Outer.Inner iner = new Outer.Inner(); // what will be InnerTestVariable value in this case? There is no instance of Outer class, and TestVariable can exist only in instance of Outer 

这里是做

class Outer 
    { 
     internal int TestVariable=0; 
     internal class Inner 
     { 
      public Inner(int testVariable) 
      { 
       InnerTestVariable = testVariable; 
      } 
      int InnerTestVariable; //Need to access the variabe "TestVariable" here 
     } 
     internal Inner CreateInner() 
     { 
      return new Inner(TestVariable); 
     } 
    } 

简答的方法之一:没有,

你会以某种方式需要将TestVariable注入到您的内部类。让你的testVariable可能会导致不希望的行为。我的消化可以通过构造函数注入。