Home > database >  How to make a class that waits for instance to be created to instantiate variables?
How to make a class that waits for instance to be created to instantiate variables?

Time:08-12

I am trying to create a class with some subclasses for a color management system in my application.

I need to create a "Colorset" object that has some "Category" objects inside of it. The problem is I need to access members of one of the categories from another category.

Since I want to be able to set the values of the "Category" members when instantiating a new "Colorset", I can't make them static.

Here's an example of what I want to do.

public class Colorset
{
    public General General { get; set; }
    public Page Page { get; set; }
}

public class General
{
    public Color Primary = Color.FromArgb("#399ed6");
    public Color Secondary = Color.FromArgb("#fff");
    public Color Text = Color.FromArgb("#000");
}

public class Page
{
    public Color TitleBar = General.Primary; // General not static, cant access it
    public Color TitleBarText = General.Secondary;
}

I want to set the TitleBar value to the value of "Primary" FROM THE COLORSET PARENT. I know a Page will always have a Colorset parent, and I want to access the value of Primary that has been set in the parent colorset.

This would be an example on how I want to instantiate a new Colorset:

Colorset = new()
{
    General = new()
    {
         Primary = Color.FromArgb("#fff"),
         Secondary = Color.FromArgb("#000")
    }
    Page = new()
    {
         TitleBar = Color.FromArgb("#123")
         // Since TitleBarText not set it defaults to the value of "Secondary"
}

How can I achieve something like this? Thanks in advance

CodePudding user response:

create a constructor for Page that accepts a General parameter

public Page(General general)
{
  TitleBarText = general.Secondary;
}

and pass in the reference when ColorSet creates Page

Page = new Page(this.General);
  • Related