开发者

How do inner classes work in c#?

If I have a class like:

public class C1
{
    public class SC1 {}
    public class SC2 {}

    p开发者_开发百科ublic class C1()
    {

    }

}

Why can't I do this:

C1 c1 = new C1();

c1.SC1.somePropety = 1234;


SC1 is a type definition. You still need to instantiate the type as a variable.

edit: delnan makes another point - if SC1 had "someProperty" declared as static, then that would also work.


Because you have created a Class, but not a property for that class.

Try

public class C1
{
  public class SC1 {}
  public class SC2 {}

  public SC1 sc1;

  public C1() {};
}

C1 c1 = new C1();
c1.sc1.SomeProperty = 1234'


I suggest reading the relevant articles on the MSDN for information about nested classes:

  • Nested Types (C# Programming Guide)
  • Implementing Nested Classes
  • Nested Classes in Components
  • Recommendations on Nested Classes in Components


C1, C1.SC1 and C1.SC2 are independent classes. In the case of C1.SC1 and C1.SC2, the outer C1 class acts as a strange kind of namespace.

You still need to create an instance of C1.SC1 (new C1.SC1().someProperty = 1234) in order to access non-static members on it.

(However, one feature that inner classes have is the ability to access private members on instances of the outer class. Inner and outer classes are still independent -- it's just that, within the scope of an inner class, private starts acting like public.)


Tutorial on Nested Classes in C#

It should be something like this:

class Demo
{
    public static void Main()
    {
        System.Console.WriteLine(OuterClass.NestedClass.x);     
    }
}

class OuterClass
{
    public class NestedClass
    {
        public static int x = 100;
    }
}

The instance class is not required to access static variables. The rules that apply to standalone classes in case of static variables also apply to nested classes. For nested classes, fully qualified names of nested classes must be used to access the static variables as shown by the above program.

Apply to your example to use that someProperty.

Edit: I also noticed that your constructor definition is wrong for C1. You cannot define class on your constructor inside the class otherwise you'll get an error like this:

'C1': member names cannot be the same as their enclosing type
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜