嵌套类型问题 [英] Nested type problem

查看:145
本文介绍了嵌套类型问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just tried to create this simple implementation:

class Test
{
   private int abc = 0;

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

如果我编译它,它会抱怨:

If I compile it, it will complain:

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

Cannot access a non-static member of outer type 'A.Test' via nested type 'B.Test.TestClass'

我不喜欢设定的方案:静态INT ABC = 0;

I dont like the solution of setting: static int abc = 0;

对此有任何其他的解决办法?

Is there any other solution for this?

推荐答案

您是大概从一个Java的背景,其中预期该代码会工作来了。

You are probably coming from a Java background where this code would work as expected.

在C#中,嵌套类型的静态的(在Java中的说法)的,即它们不绑定到父类的一个实例。这就是为什么你的代码失败。您需要父类的一个实例以某种方式传递给子类和访问的及其的成员 ABC

In C#, nested types are static (in the parlance of Java), i.e. they are not bound to an instance of the parent class. This is why your code fails. You need to somehow pass an instance of the parent class to the child class and access its member abc.

这篇关于嵌套类型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆