【问题标题】:Nested type problem嵌套类型问题
【发布时间】:2011-03-22 15:16:33
【问题描述】:

我只是尝试创建这个简单的实现:

class Test
{
   private int abc = 0;

   public class TestClass
   {
      private void changeABC()
      {
         abc = 123;
      }
   }
}

如果我编译它,它会报错:

无法通过嵌套类型“B.Test.TestClass”访问外部类型“A.Test”的非静态成员

我不喜欢设置的解决方案:static int abc = 0;

还有其他解决办法吗?

【问题讨论】:

  • @Cyber​​Drew:错误中说明了这一点:A = Test, B = Test.TestClass"

标签: c# nested-class


【解决方案1】:

您可能来自 Java 背景,此代码可以按预期工作。

在 C# 中,嵌套类型是 static(用 Java 的说法),即它们不绑定到父类的实例。这就是您的代码失败的原因。您需要以某种方式将父类的实例传递给子类并访问 its 成员 abc

【讨论】:

    【解决方案2】:

    内部类需要一个外部类实例的引用:

    class Test
    {
       private int abc = 0;
    
       public class TestClass
       {
          private void changeABC(Test test)
          {
             test.abc = 123;
          }
       }
    }
    

    【讨论】:

    • 天哪,你们真快!我花了整整4分钟!也许我应该学会触摸打字! =(
    【解决方案3】:

    我不明白为什么 TestClass 应该在父 Test 是实例类时更改它。

    也许我的例子可以说明这一点:

    class Test
    {
       public Test()
       {
         TestClass test = new TestClass();//create a new **instance** here
         test.changeABC(this);//give the instance of Test to TestClass
         Console.WriteLine(abc);//will print 123 
       }
       int abc = 0;
    
       public class TestClass
       {
          public void changeABC(Test t)
          {
             t.abc = 123;
          }
       }
    }
    

    这样使用:

    Test theTest = new Test();
    

    【讨论】:

      【解决方案4】:

      来自C# nested classes are like C++ nested classes, not Java inner classes

      当你在里面声明一个类时 另一个类,内部类仍然 表现得像普通班级。嵌套 控制访问和可见性,但 不是行为。换句话说,所有的 你学到的规则 类也适用于嵌套类。

      在Java中,内部类有一个秘密 这个 $0 会员,它记得 外部类的实例 它被绑定了。

      换句话说,Java 内部类是 不可用的语法糖 到 C#。在 C# 中,你必须这样做 手动。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-16
        • 1970-01-01
        • 1970-01-01
        • 2015-12-28
        • 2019-08-11
        • 2016-09-08
        相关资源
        最近更新 更多