개체 필드를 함수 매개 변수로 사용 다른 필드 [중복]

Jan 03 2021

새로운 객체 필드를 함수 매개 변수로 다른 필드로 사용할 수 있습니까 (이 같은 객체 초기화에서)?

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

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

답변

Sisir Jan 03 2021 at 00:56

현재 코드 디자인으로는 불가능합니다. 그 이유는 개체가 완전히 생성되기 전에 다른 필드에있는 개체의 한 필드를 참조 할 수 없기 때문입니다. 이는 클래스 수준 varibales로 선언하는 동안 다른 필드 값을 사용할 수없는 이유와 동일합니다.

그러나 원하는 것을 달성 할 수있는 방법이 있습니다.

옵션 1:

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

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

옵션 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 "";
        }
    }