Readonly field that could be assigned a value outside constructor

后端 未结 7 1894
清酒与你
清酒与你 2021-01-22 16:19

Is there a way to have a private readonly field in a class that could be assigned a value anywhere in the class, but only once??

That is, I am looking for a private read

7条回答
  •  不思量自难忘°
    2021-01-22 17:07

    I think I achieved a way to do it, if it is done in the constructor. It could also be on the variable declaration line. If done outside those contexts, you will receive an error: A readonly field cannot be assigned to (except in a constructor or a variable initializer)

    public class BillLine
    {
        public BillLine(Bill bill)
        {
            m_Bill = bill;
        }
    
        private readonly Bill m_Bill;
    
        public Bill Bill
        {
            get { return m_Bill; }
    
            //supposed to be set only in the constructor
        }
    
        //(...)
    }
    

提交回复
热议问题