Vienna

7일차 본문

언어/이것이 C#이다

7일차

아는개발자 2021. 12. 4. 23:44

1. 실습_Property

using System;

namespace _9장_Property_326page
{
    class BirthdayInfo
    { 
        private string name;
        private DateTime birthday;

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        public DateTime Birthday
        {
            get
            {
                return birthday;
            }
            set
            {
                birthday = value;
            }
        }

        public int Age
        {
            get
            {
                return new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            BirthdayInfo birth = new BirthdayInfo();
            birth.Name = "서현";
            birth.Birthday = new DateTime(1991, 6, 28);

            Console.WriteLine($"Name: {birth.Name}");
            Console.WriteLine($"Birthday: {birth.Birthday}");
            Console.WriteLine($"Age: {birth.Age}");
        }
    }
}

 

2. 실습_AutoImplementedProperty

using System;

namespace _9장_AutoImplementedProperty_330page
{
    class BirthdayInfo
    {
        public string Name { get; set; } = "Unkown";
        public DateTime Birthday { get; set; } = new DateTime(1,1,1);

        public int Age
        {
            get
            {
                return new DateTime(DateTime.Now.Subtract(Birthday).Ticks).Year;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            BirthdayInfo birth = new BirthdayInfo();
            Console.WriteLine($"Name: {birth.Name}");
            Console.WriteLine($"Birthday: {birth.Birthday.ToShortDateString()}");
            Console.WriteLine($"Age: {birth.Age}");

            birth.Name = "서현";
            birth.Birthday = new DateTime(1991, 6, 28);

            Console.WriteLine($"Name: {birth.Name}");
            Console.WriteLine($"Birthday: {birth.Birthday.ToShortDateString()}");
            Console.WriteLine($"Age: {birth.Age}");
        }
    }
}

 

3. 실습_ConstructorWithProperty

using System;

namespace _9장_ConstructorWithProperty_333page
{
    class Program
    {
        class BirthdayInfo
        {
            public string Name
            {
                get;
                set;
            }

            public DateTime Birthday
            {
                get;
                set;
            }
            public int Age
            {
                get
                {
                    return new DateTime(DateTime.Now.Subtract(Birthday).Ticks).Year;
                }
            }
        }

        static void Main(string[] args)
        {
            BirthdayInfo birth = new BirthdayInfo()
            {
                Name = "서현",
                Birthday = new DateTime(1991, 6, 28)
            };

            Console.WriteLine($"Name: {birth.Name}");
            Console.WriteLine($"Birthday: {birth.Birthday.ToShortDateString()}");
            Console.WriteLine($"Age: {birth.Age}");
        }
    }
}

 

4. 실습_InitOnly

using System;

namespace _9장_InitOnly_336page
{
    class Transaction
    {
        public string From { get; init; }
        public string To { get; init; }
        public int Amount { get; init; }

        public override string ToString()
        {
            return $"{From,-10} -> {To,-10} : ${Amount}";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Transaction tr1 = new Transaction { From = "Alice", To = "Bob", Amount = 100 };
            Transaction tr2 = new Transaction { From = "Bob", To = "Charlie", Amount = 50 };
            Transaction tr3 = new Transaction { From = "Charlie", To = "Alice", Amount = 50 };

            Console.WriteLine(tr1);
            Console.WriteLine(tr2);
            Console.WriteLine(tr3);
        }
    }
}

와 진짜 편하고 재밌다... 읽기 전용은 클래스 내부에서 초기화하게 만들고 get만 만드나 그럼 좀 불편하지 않나 생각하고 있었는데 init이 있었어...

 

5. 실습_WithExp

using System;

namespace _9장_WithExp_340page
{
    record RTransaction
    {
        public string From { get; init; }
        public string To { get; init; }
        public int Amount { get; init; }

        public override string ToString()
        {
            return $"{From,-10} -> {To,-10} : ${Amount}";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            RTransaction tr1 = new RTransaction { From = "Alice", To = "Bob", Amount = 100 };
            RTransaction tr2 = tr1 with { To = "Charlie" };
            RTransaction tr3 = tr2 with { From = "Dave", Amount=30 };

            Console.WriteLine(tr1);
            Console.WriteLine(tr2);
            Console.WriteLine(tr3);
        }
    }
}

 

6. 실습_RecordComp

using System;

namespace _9장_RecordComp_343page
{
    class CTransaction
    {
        public string From { get; init; }
        public string To { get; init; }
        public int Amount { get; init; }

        public override string ToString()
        {
            return $"{From,-10} -> {To,-10} : ${Amount}";
        }
    }
    record RTransaction
    {
        public string From { get; init; }
        public string To { get; init; }
        public int Amount { get; init; }

        public override string ToString()
        {
            return $"{From,-10} -> {To,-10} : ${Amount}";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            CTransaction trA = new CTransaction { From = "Alice", To = "Bob", Amount = 100 };
            CTransaction trB = new CTransaction { From = "Alice", To = "Bob", Amount = 100 };

            Console.WriteLine(trA);
            Console.WriteLine(trB);
            Console.WriteLine($"trA equals to trB : {trA.Equals(trB)}");

            RTransaction tr1 = new RTransaction { From = "Alice", To = "Bob", Amount = 100 };
            RTransaction tr2 = new RTransaction { From = "Alice", To = "Bob", Amount = 100 };

            Console.WriteLine(tr1);
            Console.WriteLine(tr2);
            Console.WriteLine($"tr1 equals to tr2 : {tr1.Equals(tr2)}");
        }
    }
}

 

7. 실습_AnonymousType

using System;

namespace _9장_AnonymousType_345page
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = new { Name = "박상현", Age = 123 };
            Console.WriteLine($"Name: {a.Name}, Age: {a.Age}");

            var b = new { Subject = "수학", Scores = new int[] { 90, 80, 70, 60 } };

            Console.Write($"Subject: {b.Subject}, Scores: ");
            foreach (var score in b.Scores)
                Console.Write($"{score} ");

            Console.WriteLine();
        }
    }
}

 

8. 실습_PropertiesInInterface

using System;

namespace _9장_PropertiesInInterface_348page
{
    interface INamedValue
    {
        string Name { get; set; }
        string Value { get; set; }
    }

    class NamedValue : INamedValue
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            NamedValue name = new NamedValue()
            { Name="이름", Value="박상현" };

            NamedValue height = new NamedValue()
            { Name = "키", Value = "177cm" };

            NamedValue weight = new NamedValue()
            { Name = "몸무게", Value = "90kg" };

            Console.WriteLine($"{name.Name}: {name.Value}");
            Console.WriteLine($"{height.Name}: {height.Value}");
            Console.WriteLine($"{weight.Name}: {weight.Value}");
        }
    }
}

ㅠㅠ 진짜 재밌다 너무 신기하네... 확실히 뭔가 실용적이고 간편해진 느낌이다

 

9. 실습_PropertiesInAbstractClass

using System;

namespace _9장_PropertiesInAbstractClass_351page
{
    abstract class Product
    {
        private static int serial = 0;
        public string SerialID
        {
            get { return String.Format("{0:d5}", serial++); }
        }

        abstract public DateTime ProductDate
        {
            get;
            set;
        }
    }

    class MyProduct : Product
    {
        public override DateTime ProductDate
        {
            get; set;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Product product1 = new MyProduct()
            { ProductDate = new DateTime(2018, 1, 10) };

            Console.WriteLine("Product: {0}, Product Date: {1}", product1.SerialID, product1.ProductDate);

            Product product2 = new MyProduct()
            { ProductDate = new DateTime(2018, 2, 3) };

            Console.WriteLine("Product: {0}, Product Date: {1}", product2.SerialID, product2.ProductDate);
        }
    }
}

음... 사실 나 아직도 기반클래스 참조가 파생클래스 객체의 값을 참조하는 거 이해를 제대로 못한 것 같다. 이론적으로는 알겠는데 정확히 내 것으로 만든 게 안 된 느낌. 그래서 이걸 활용하는 내용이 나올 때마다 조금씩 딜레이가 생기는데... 한 번더 복습이 필요할 것 같다. 나중에 복습할 때 이 내용도 한 번 더 훑어봐야겠다.

 

10. 연습문제1

다음 코드에서 NameCard 클래스의 GetAge(), SetAge(), GetName(), SetName() 메소드를 프로퍼티로 변경해 작성하세요.
using System;

namespace 연습문제1_353page
{
    class NameCard
    {
        private int age;
        private string name;

        public int GetAge() { return age; }
        public void SetAge(int value) { age = value; }
        public string GetName() { return name; }
        public void SetName(string value) { name = value; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            NameCard MyCard = new NameCard();

            MyCard.SetAge(24);
            MyCard.SetName("상현");

            Console.WriteLine("나이: {0}", MyCard.GetAge());
            Console.WriteLine("이름: {0}", MyCard.GetName());
        }
    }
}

내 답변:

using System;

namespace 연습문제1_353page
{
    class NameCard
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            NameCard MyCard = new NameCard();

            MyCard.Age=24;
            MyCard.Name="상현";

            Console.WriteLine("나이: {0}", MyCard.Age);
            Console.WriteLine("이름: {0}", MyCard.Name);
        }
    }
}
using System;

namespace 연습문제1_353page
{
    class NameCard
    {
        private int age;
        private string name;
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            NameCard MyCard = new NameCard();

            MyCard.Age=24;
            MyCard.Name="상현";

            Console.WriteLine("나이: {0}", MyCard.Age);
            Console.WriteLine("이름: {0}", MyCard.Name);
        }
    }
}

자동구현 프로퍼티 말고도 써 봤다. 그냥 하고 싶어서

 

11. 연습문제2

다음 프로그램을 완성해서 다음과 같은 결과를 출력하도록 하세요. 단, 무명 형식을 이용해야 합니다.

이름:박상현, 나이:17
Real:3, Imaginary:-12
using System;

namespace 연습문제2_353page
{
    class Program
    {
        static void Main(string[] args)
        {
            var nameCard = new { Name = "박상현", Age = 17 };
            Console.WriteLine("이름:{0}, 나이:{1}", nameCard.Name, nameCard.Age);

            var complex = new { Real = 3, Imaginary = -12 };
            Console.WriteLine("Real:{0}, Imaginary:{1}", complex.Real, complex.Imaginary);
        }
    }
}

'언어 > 이것이 C#이다' 카테고리의 다른 글

8일차  (0) 2021.12.05
6일차  (0) 2021.12.03
5일차  (0) 2021.11.30
4일차  (0) 2021.11.25
3일차  (0) 2021.11.24
Comments