问题
I have three classes like this.
class A
{
public class innerB
{
//Do something
}
public class innerC
{
//trying to access objB here directly or indirectly over here.
//I dont have to create an object of innerB, but to access the object created by A
//i.e.
innerB objInnerB = objB;
//not like this
innerB objInnerB= new innerB();
}
private innerB objB{get;set;} **//Private**
public A()
{
objB= new innerB();
}
}
I want to access the object of class B in Class C that is created by class A. Is it possible somehow to make changes on object of Class A in Class C. Can i get Class A's object by creating event or anyhow.
Edit: My mistake in asking the question above. Object of B created in A is private not public
IS IT POSSIBLE TO DO THIS BY CREATING EVENT
If anyhow I become able to raise an event that can be handled by Class A, then my problem can be solved.
回答1:
If I'm reading you correctly you want to access the objB property of class A within innerC WITHOUT passing it along.
This isn't how C# inner classes work, as described in this article: C# nested classes are like C++ nested classes, not Java inner classes
If you want to access A.objB from innerC then you are going to have to somehow pass class A to innerC.
回答2:
You need to pass a reference of OuterClass
to InnerClass
, perhaps in the constructor, like:
public class OuterClass
{
//OuterClass methods
public class InnerClass
{
private OuterClass _outer;
public InnerClass(OuterClass outer)
{
_outer = outer;
}
}
}
Then you can use that reference in all of your InnerClass
methods.
回答3:
Since your class B is within the same scope as class C, that is, within class A, you will be able to instantiate the nested type B from nested type C and use it.
来源:https://stackoverflow.com/questions/2957900/can-i-access-outer-class-objects-in-inner-class