Używanie pola obiektu jako parametru funkcji inne pole [duplikat]

Jan 03 2021

Czy jest możliwe użycie nowego pola obiektu jako parametru funkcji inne pole (w tej samej inicjalizacji obiektu)?

List<Reservations> reservations = new List<Reservations>()
 {
  new Reservations{title="Grooming", className=checkColor(title)},
 };

public string checkColor(string title)
{
 ...
}         

Odpowiedzi

Sisir Jan 03 2021 at 00:56

Nie jest to możliwe przy obecnym projekcie Twojego kodu. Powodem jest to, że nie możesz odwołać się do 1 pola obiektu w innym polu, zanim obiekt nie zostanie w pełni skonstruowany. To jest to samo, dlaczego nie możemy użyć 1 wartości pola w innym, deklarując jako zmienne na poziomie klasy.

Są jednak sposoby na osiągnięcie tego, co chcesz.

Opcja 1:

const string titleText = "Grooming";
List<Reservations> reservations = new List<Reservations>()
{
    new Reservations{title=titleText, className=checkColor(titleText)},
};

private static string checkColor(string title)
{
 ...
}

Opcja 2:

    class Consumer
    {
        List<Reservations> reservations = new List<Reservations>()
        {
            new Reservations{title="Grooming"}
        };
    }

    class Reservations
    {
        string _title;

        public string title
        {
            get
            {
                return _title;
            }

            set
            {
                _title = value;
                className = checkColor(title);
            }
        }

        public string className;

        private string checkColor(string title)
        {
            return "";
        }
    }