简体   繁体   中英

Access to members of a nested class that are public

I have something like this:

public class OuterClass
{
   // other methods and fields... 

    public class InnerClass {
        public int Prop1 {get; set;}
        public int Prop2 {get; set;}
    }
}

and then in a method I have an object being passed that is of type OuterClass . I thought I can write something like this. But intellisense is not showing it.

outerClassobject.InnerClass.Prop1 = 234;

You are mixing classes and objects. You need to access fields or properties of an object:

OuterClass.InnerClass innerClassObject = new OuterClass.InnerClass();
innerClassObject.Prop1 = 234;

Or:

public class OuterClass
{
   // other methods and fields... 
    public InnerClass InnerClassProp { get; } = new InnerClass();

    public class InnerClass {
        public int Prop1 { get; set; }
        public int Prop2 { get; set; }
    }
}

outerClassobject.InnerClassProp.Prop1 = 234;

When you want to access a property of the inner class, you need an instance of it. So in the above example OuterClass.InnerClass is instantiated and assigned to InnerClassProp .

In your example, the classes are nested. That does not necessarily mean that the instances are nested, too. Conversely, it is also possible that the instances are nested, but the classes are not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM