问题
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?
回答1:
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
.
回答2:
The inner class needs a reference to an instance of the outer class:
class Test
{
private int abc = 0;
public class TestClass
{
private void changeABC(Test test)
{
test.abc = 123;
}
}
}
回答3:
I don't see why TestClass
should change the parent Test
when its an instance class.
Maybe me example would shed light on this:
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;
}
}
}
Use Like this:
Test theTest = new Test();
回答4:
From C# nested classes are like C++ nested classes, not Java inner classes
When you declare a class inside another class, the inner class still acts like a regular class. The nesting controls access and visibility, but not behavior. In other words, all the rules you learned about regular classes also apply to nested classes.
In Java, the inner class has a secret this$0 member which remembers the instance of the outer class to which it was bound.
In other words, Java inner classes are syntactic sugar that is not available to C#. In C#, you have to do it manually.
来源:https://stackoverflow.com/questions/5393432/nested-type-problem