Develop Dairy/C#

[Csharp] Readonly, const

ํ‰์ƒ์ฝ”๋”ฉ 2021. 12. 30. 01:22

๐Ÿ“–C# Readonly, Const

Readonly

  1. ์ฝ๊ธฐ ์ „์šฉ ๋ณ€์ˆ˜๋Š” initializer, ์ƒ์„ฑ์ž ๋ฉ”์„œ๋“œ์— ํ• ๋‹น ๊ฐ€๋Šฅ
  2. ์ฝ๊ธฐ ์ „์šฉ ๋ณ€์ˆ˜๋Š” ์—ฌ๋Ÿฌ๋ฒˆ ์žฌ์ •์˜ ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.
public class Readonly
{
    private readonly ExampleObject _exampleObjecct = new ExampleObject() { Id = 1 };

    public Readonly()
    {
        // _exampleObjecct๋ณ€์ˆ˜๋ฅผ ์žฌ์ •์˜ ํ•˜๋Š” ๋ชจ์Šต
        _exampleObjecct = new ExampleObject( Id = 2);
        _exampleObjecct = new ExampleObject( Id = 3);
    }
}

public class ExampleObject
{
    public int id {get; set;}
}
  1. ๋ฉ”์„œ๋“œ ๋ฐ–์—์„œ๋Š” ์žฌ์ •์˜๋ฅผ ํ•  ์ˆ˜ ์—†์Œ

Const

  1. const ๋ณ€์ˆ˜ (์ƒ์ˆ˜)๋Š” ๋Ÿฐํƒ€์ž„์—์„œ ์ƒ์„ฑ๋˜๊ธฐ ๋•Œ๋ฌธ์— ์ฐธ์กฐ๋ฅผ ํ•  ์ˆ˜ ์—†๋‹ค. (์žฌํ• ๋‹น ๋ถˆ๊ฐ€ )

  2. ์ƒ์ˆ˜๋ณ€์ˆ˜๋Š” ์ •์ ๋ณ€์ˆ˜๋กœ ํ•  ์ˆ˜ ์—†๋‹ค.

  3. ์ปดํŒŒ์ผ๋Ÿฌ๋Š” IL ์ฝ”๋“œ(์ค‘๊ฐ„ ์–ธ์–ด)๋ฅผ ์ƒ์„ฑํ• ๋•Œ "const" ๋ณ€์ˆ˜์˜ ๋ชจ๋“  ์ฐธ์กฐ๋ฅผ ํ•ด๋‹น ๊ฐ’์œผ๋กœ ๋ฐ”๊พผ๋‹ค.

  4. ์‚ฌ์šฉ

    public class ConstClass
    {
        private const string _constString = "const";
    
        public ConstClass()
        {
            Console.WriteLine(_constString);
        }
    }
  5. const๊ฐ€ ์ฐธ์กฐ๋œ ๋ณ€์ˆ˜๋“ค์ด ์žˆ๋‹ค๋ฉด ๋นŒ๋“œ๋ฅผ ๋‹ค์‹œ ํ•ด์•ผ ํ•จ. (์•ฑ ๋ฒ„์ „์ด ๋ฐ”๋€”๋•Œ ๋ผ๋“ ๊ฐ€..)