简体   繁体   中英

A class has a field/property the same as its own type?

I'm confused about this statement:

ctrlID.Font.Size = FontUnit.Small;

but FontUnit is a struct under System.Web.UI.WebControls

public struct FontUnit
{
   ...
   public static readonly FontUnit Small;
   ...
}

as a struct is a class, so how can we have a class A that has its self as a object like:

public class A{
   public A a;
}

isn't it like creating an endless chain of objects which would require infinite memory?

The property is static , so it's a member of the Type, and not of the object instance. You do not need to construct the Small static property to create a FontUnit object.

Consider this:

public class Foo 
{
    public static Foo Default {get;}
    static Foo() 
    {
         Default = new Foo();
    }
}

Default is only constructed once, at an unknown time before it is used.

If it's not static, you can get into the behavior you expected.

public class Foo 
{
    public Foo Default {get; private set;}
    public Foo() 
    {
        Default = new Foo();
    }
}

This will cause an overflow, as the property will keep instantiating a new Foo , which will make a new Foo , and so on.

So long as you're careful not to instantiate a type with the same constructor you are currently instantiating a type in there shouldn't be any issue with a type having member of it's own type.

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