Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

c# - Nested type problem

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:

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

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

Is there any other solution for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...