Vienna
5일차 본문
1. 실습_BasicClass
using System;
namespace _7장_BasicClass_225page
{
class Cat
{
public string Name;
public string Color;
public void Meow()
{
Console.WriteLine($"{Name}: 야옹");
}
}
class Program
{
static void Main(string[] args)
{
Cat kitty = new Cat();
kitty.Color = "하얀색";
kitty.Name = "키티";
kitty.Meow();
Console.WriteLine($"{kitty.Name}: {kitty.Color}");
Cat nero = new Cat();
nero.Color = "검은색";
nero.Name = "네로";
nero.Meow();
Console.WriteLine($"{nero.Name}: {nero.Color}");
}
}
}
2. 실습_Constructor
using System;
namespace _7장_Constructor_229page
{
class Cat
{
public Cat()
{
Name = "";
Color = "";
}
public Cat(string _Name, string _Color)
{
Name = _Name;
Color = _Color;
}
~Cat()
{
Console.WriteLine($"{Name}: 잘가");
}
public string Name;
public string Color;
public void Meow()
{
Console.WriteLine($"{Name}: 야옹");
}
}
class Program
{
static void Main(string[] args)
{
Cat kitty = new Cat("키티","하얀색");
kitty.Meow();
Console.WriteLine($"{kitty.Name}: {kitty.Color}");
Cat nero = new Cat("네로","검은색");
nero.Meow();
Console.WriteLine($"{nero.Name}: {nero.Color}");
}
}
}
3. 실습_StaticField
using System;
namespace _7장_StaticField_233page
{
class Global
{
public static int Count = 0;
}
class ClassA
{
public ClassA()
{
Global.Count++;
}
}
class ClassB
{
public ClassB()
{
Global.Count++;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Global.Count: {Global.Count}");
new ClassA();
new ClassA();
new ClassB();
new ClassB();
Console.WriteLine($"Global.Count: {Global.Count}");
}
}
}
4. 실습_DeepCopy
using System;
namespace _7장_DeepCopy_237page
{
class MyClass
{
public int MyField1;
public int MyField2;
public MyClass DeepCopy()
{
MyClass newCopy = new MyClass();
newCopy.MyField1 = this.MyField1;
newCopy.MyField2 = this.MyField2;
return newCopy;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Shallow Copy");
{
MyClass source = new MyClass();
source.MyField1 = 10;
source.MyField2 = 20;
MyClass target = source;
target.MyField2 = 30;
Console.WriteLine($"{source.MyField1}, {source.MyField2}");
Console.WriteLine($"{target.MyField1}, {target.MyField2}");
}
Console.WriteLine("Deep Copy");
{
MyClass source = new MyClass();
source.MyField1 = 10;
source.MyField2 = 20;
MyClass target = source.DeepCopy();
target.MyField2 = 30;
Console.WriteLine($"{source.MyField1}, {source.MyField2}");
Console.WriteLine($"{target.MyField1}, {target.MyField2}");
}
}
}
}
5. 실습_This
using System;
namespace _7장_This_240page
{
class Program
{
class Employee
{
private string Name;
private string Position;
public void SetName(string Name)
{
this.Name = Name;
}
public string GetName()
{
return this.Name;
}
public void SetPosition(string Position)
{
this.Position = Position;
}
public string GetPosition()
{
return this.Position;
}
}
static void Main(string[] args)
{
Employee pooh = new Employee();
pooh.SetName("Pooh");
pooh.SetPosition("Waiter");
Console.WriteLine($"{pooh.GetName()}: {pooh.GetPosition()}");
Employee tigger = new Employee();
tigger.SetName("Tigger");
tigger.SetPosition("Cleaner");
Console.WriteLine($"{tigger.GetName()}: {tigger.GetPosition()}");
}
}
}
6. 실습_ThisConstructor
using System;
namespace _7장_ThisConstructor_243page
{
class MyClass
{
int a, b, c;
public MyClass()
{
this.a = 5425;
Console.WriteLine("MyClass()");
}
public MyClass(int b) : this()
{
this.b = b;
Console.WriteLine($"MyClass(int {b})");
}
public MyClass(int b, int c) : this(b)
{
this.c = c;
Console.WriteLine($"MyClass(int {b}, int {c})");
}
public void PrintFields()
{
Console.WriteLine($"a: {a}\nb: {b}\nc: {c}");
}
}
class Program
{
static void Main(string[] args)
{
MyClass a = new MyClass();
a.PrintFields();
Console.WriteLine();
MyClass b = new MyClass(1);
b.PrintFields();
Console.WriteLine();
MyClass c = new MyClass(10,20);
c.PrintFields();
Console.WriteLine();
}
}
}
7. 실습_AccessModifier
using System;
namespace _7장_AccessModifier_247page
{
class WaterHeater
{
protected int temperature;
public void SetTemperature(int temperature)
{
if(temperature<-5 || temperature>42)
{
throw new Exception("Out of temperature range");
}
this.temperature = temperature;
}
internal void TurnOnWater()
{
Console.WriteLine($"Turn on water: {temperature}");
}
}
class Program
{
static void Main(string[] args)
{
try
{
WaterHeater heater = new WaterHeater();
heater.SetTemperature(20);
heater.TurnOnWater();
heater.SetTemperature(-2);
heater.TurnOnWater();
heater.SetTemperature(50);
heater.TurnOnWater();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
8. 실습_Inheritance
using System;
namespace _7장_Inheritance_253page
{
class Base
{
protected string Name;
public Base(string Name)
{
this.Name = Name;
Console.WriteLine($"{this.Name}.Base()");
}
~Base()
{
Console.WriteLine($"{this.Name}.~Base()");
}
public void BaseMethod()
{
Console.WriteLine($"{Name}.BaseMethod");
}
}
class Derived : Base
{
public Derived(string Name): base (Name)
{
Console.WriteLine($"{this.Name}.Derved()");
}
~Derived()
{
Console.WriteLine($"{this.Name}.~Derived()");
}
public void DerivedMethod()
{
Console.WriteLine($"{Name}.DerivedMethod()");
}
}
class Program
{
static void Main(string[] args)
{
Base a = new Base("a");
a.BaseMethod();
Derived b = new Derived("b");
b.BaseMethod();
b.DerivedMethod();
}
}
}
9. 실습_TypeCasting
using System;
namespace _7장_TypeCasting_258page
{
class Program
{
class Mammal
{
public void Nurse()
{
Console.WriteLine("Nurse()");
}
}
class Dog : Mammal
{
public void Bark()
{
Console.WriteLine("Bark()");
}
}
class Cat : Mammal
{
public void Meow()
{
Console.WriteLine("Meow()");
}
}
static void Main(string[] args)
{
Mammal mammal = new Dog();
Dog dog;
if(mammal is Dog)
{
dog = (Dog)mammal;
dog.Bark();
}
Mammal mammal2 = new Cat();
Cat cat = mammal2 as Cat;
if (cat != null)
cat.Meow();
Cat cat2 = mammal as Cat;
if (cat2 != null)
cat2.Meow();
else
Console.WriteLine("cat2 is not a Cat");
}
}
}
10. 실습_Overriding
using System;
namespace _7장_Overriding_262page
{
class ArmorSuite
{
public virtual void Initialize()
{
Console.WriteLine("Armored");
}
}
class IronMan : ArmorSuite
{
public override void Initialize()
{
base.Initialize();
Console.WriteLine("Repulsor Rays Armed");
}
}
class WarMachine : ArmorSuite
{
public override void Initialize()
{
base.Initialize();
Console.WriteLine("Double-Barrel Cannons Armed");
Console.WriteLine("Micro-Rocket Launcher Armed");
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Creating ArmorSuite...");
ArmorSuite armorsuite = new ArmorSuite();
armorsuite.Initialize();
Console.WriteLine("\nCreating IronMan...");
ArmorSuite ironman = new IronMan();
ironman.Initialize();
Console.WriteLine("\nCreating WarMachine...");
ArmorSuite warmachine = new WarMachine();
warmachine.Initialize();
}
}
}
11. 실습_MethodHiding
using System;
namespace _7장_MethodHiding_265page
{
class Base
{
public void MyMethod()
{
Console.WriteLine("Base.MyMethod()");
}
}
class Derived : Base
{
public new void MyMethod()
{
Console.WriteLine("Derived.MyMethod()");
}
}
class Program
{
static void Main(string[] args)
{
Base baseObj = new Base();
baseObj.MyMethod();
Derived derivedObj = new Derived();
derivedObj.MyMethod();
Base baseOrDerived = new Derived();
baseOrDerived.MyMethod();
}
}
}
12. 실습_SealedMethod_컴파일 에러
using System;
namespace _7장_SealedMethod_267page
{
class Base
{
public virtual void SealMe()
{ }
}
class Derived : Base
{
public sealed override void SealMe()
{ }
}
class WantToOverride : Derived
{
public override void SealMe()
{ }
}
class Program
{
static void Main(string[] args)
{
}
}
}
13. 실습_ReadonlyFields_컴파일 에러
using System;
namespace _7장_ReadonlyFields_270page
{
class Configuration
{
private readonly int min;
private readonly int max;
public Configuration(int v1, int v2)
{
min = v1;
max = v2;
}
public void ChangeMax(int newMax)
{
max = newMax;
}
}
class Program
{
static void Main(string[] args)
{
Configuration c = new Configuration(100, 10);
}
}
}
14. 실습_NestedClass
using System;
using System.Collections.Generic;
namespace _7장_NestedClass_272page
{
class Program
{
class Configuration
{
List<ItemValue> listConfig = new List<ItemValue>();
public void SetConfig(string item, string value)
{
ItemValue iv = new ItemValue();
iv.SetValue(this, item, value);
}
public string GetConfig(string item)
{
foreach (ItemValue iv in listConfig)
{
if (iv.GetItem() == item)
return iv.GetValue();
}
return "";
}
private class ItemValue
{
private string item;
private string value;
public void SetValue(Configuration config, string item, string value)
{
this.item = item;
this.value = value;
bool found = false;
for (int i = 0; i < config.listConfig.Count;i++)
{
if(config.listConfig[i].item==item)
{
config.listConfig[i] = this;
found = true;
break;
}
}
if (found == false)
config.listConfig.Add(this);
}
public string GetItem()
{
return item;
}
public string GetValue()
{
return value;
}
}
}
static void Main(string[] args)
{
Configuration config = new Configuration();
config.SetConfig("Version", "V 5.0");
config.SetConfig("Size", "655,324 KB");
Console.WriteLine(config.GetConfig("Version"));
Console.WriteLine(config.GetConfig("Size"));
config.SetConfig("Version", "V 5.0.1");
Console.WriteLine(config.GetConfig("Version"));
}
}
}
15. 실습_PartialClass
using System;
namespace _7장_PartialClass_275page
{
class Program
{
partial class MyClass
{
public void Method1()
{
Console.WriteLine("Method1");
}
public void Method2()
{
Console.WriteLine("Method2");
}
}
partial class MyClass
{
public void Method3()
{
Console.WriteLine("Method3");
}
public void Method4()
{
Console.WriteLine("Method4");
}
}
static void Main(string[] args)
{
MyClass obj = new MyClass();
obj.Method1();
obj.Method2();
obj.Method3();
obj.Method4();
}
}
}
16. 실습_ExtensionMethod
using System;
using MyExtension;
namespace MyExtension
{
public static class IntegerExtension
{
public static int Square(this int myInt)
{ return myInt * myInt; }
public static int Power(this int myInt, int exponent)
{
int result = myInt;
for (int i = 1; i < exponent; i++)
result *= myInt;
return result;
}
}
}
namespace _7장_ExtensionMethod_278page
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"3^2: { 3.Square()}");
Console.WriteLine($"3^4: { 3.Power(4)}");
Console.WriteLine($"2^10: { 2.Power(10)}");
}
}
}
17. 비타민 퀴즈 7-2
string 클래스에 문자열 매개변수를 입력받아 기존의 문자열 뒤에 붙여 반환하는 Append() 확장 메소드를 추가해보세요. 이 확장 메소드의 사용 예는 다음과 같습니다.
string hello="Hello";
Console.WriteLine(hello.Append(", World!"));
using System;
using MyExtension;
namespace MyExtension
{
public static class IntegerExtension
{
public static int Square(this int myInt)
{ return myInt * myInt; }
public static int Power(this int myInt, int exponent)
{
int result = myInt;
for (int i = 1; i < exponent; i++)
result *= myInt;
return result;
}
}
public static class StringExtension
{
public static string Append(this string myStr, string exponent)
{
return myStr + exponent;
}
}
}
namespace _7장_ExtensionMethod_278page
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"3^2: { 3.Square()}");
Console.WriteLine($"3^4: { 3.Power(4)}");
Console.WriteLine($"2^10: { 2.Power(10)}");
string hello = "Hello";
Console.WriteLine(hello.Append(", World!"));
}
}
}
18. 실습_Strutcture
using System;
namespace _7장_Structure_281page
{
struct Point3D
{
public int X;
public int Y;
public int Z;
public Point3D(int X, int Y, int Z)
{
this.X = X;
this.Y = Y;
this.Z = Z;
}
public override string ToString()
{
return string.Format($"{X}, {Y}, {Z}");
}
}
class Program
{
static void Main(string[] args)
{
Point3D p3d1;
p3d1.X = 10;
p3d1.Y = 20;
p3d1.Z = 40;
Console.WriteLine(p3d1.ToString());
Point3D p3d2 = new Point3D(100, 200, 300);
Point3D p3d3 = p3d2;
p3d3.Z = 400;
Console.WriteLine(p3d2.ToString());
Console.WriteLine(p3d3.ToString());
}
}
}
19. 실습_ReadonlyStruct_컴파일 에러
using System;
using ReadonlyStruct;
namespace ReadonlyStruct
{
readonly struct RGBColor
{
public readonly byte R;
public readonly byte G;
public readonly byte B;
public RGBColor(byte r, byte g, byte b)
{
R = r;
G = g;
B = b;
}
}
}
namespace _7장_ReadonlyStruct_284page
{
class Program
{
static void Main(string[] args)
{
RGBColor Red = new RGBColor(255, 0, 0);
Red.G = 100;
}
}
}
20. 실습_ReadonlyMethod_컴파일 에러
using System;
namespace _7장_ReadonlyMethod_286page
{
struct ACSetting
{
public double currentInCelsius; //현재 온도
public double target; // 희망 온도
public readonly double GetFahrenheit()
{
target = currentInCelsius * 1.8 + 32;
return target;
}
}
class Program
{
static void Main(string[] args)
{
ACSetting acs;
acs.currentInCelsius = 25;
acs.target = 25;
Console.WriteLine($"{acs.GetFahrenheit()}");
Console.WriteLine($"{acs.target}");
}
}
}
21. 실습_Tuple
using System;
namespace _7장_Tuple_289page
{
class Program
{
static void Main(string[] args)
{
var a = ("슈퍼맨", 9999);
Console.WriteLine($"{a.Item1}, {a.Item2}");
var b = (Name:"박상현", Age:17);
Console.WriteLine($"{b.Name}, {b.Age}");
var (name, age) = b;
Console.WriteLine($"{name}, {age}");
var (name2, age2) = ("박문수", 34);
Console.WriteLine($"{name2}, {age2}");
b = a;
Console.WriteLine($"{b.Name}, {b.Age}");
}
}
}
22. 실습_PositionalPattern
using System;
namespace _7장_PositionalPattern_291page
{
class Program
{
private static double GetDiscountRate(object client)
{
return client switch
{
("학생", int n) when n <= 18 => 0.2,
("학생", _) => 0.1,
("일반", int n) when n <= 18 => 0.1,
("일반", _) => 0.05,
_ => 0,
};
}
static void Main(string[] args)
{
var alice = (job: "학생", age: 17);
var bob = (job: "학생", age: 23);
var charlie = (job: "일반", age: 15);
var dave = (job: "일반", age: 21);
Console.WriteLine($"alice : {GetDiscountRate(alice)}");
Console.WriteLine($"bob : {GetDiscountRate(bob)}");
Console.WriteLine($"charlie : {GetDiscountRate(charlie)}");
Console.WriteLine($"dave : {GetDiscountRate(dave)}");
}
}
}
23. 연습문제5
다음 코드를 컴파일 및 실행이 가능하도록 수정하세요.
using System;
namespace 연습문제5_294page
{
struct ACSetting
{
public double currentInCelsius; //현재 온도
public double target; // 희망 온도
public readonly double GetFahrenheit()
{
return currentInCelsius * 1.8 + 32;
}
}
class Program
{
static void Main(string[] args)
{
ACSetting acs;
acs.currentInCelsius = 25;
acs.target = 25;
Console.WriteLine($"{acs.GetFahrenheit()}");
Console.WriteLine($"{acs.target}");
}
}
}
24. 연습문제7
다음 코드에서 switch 식을 제거하고 switch 문으로 동일한 기능을 작성하세요.
using System;
namespace 연습문제7_295page
{
class Program
{
private static double GetDiscountRate(object client)
{
switch(client)
{
case ("학생", int n) when n<= 18: return 0.2;
case ("학생", _): return 0.1;
case ("일반", int n) when n <= 18: return 0.1;
case ("일반", _): return 0.05;
default: return 0;
}
}
static void Main(string[] args)
{
var alice = (job: "학생", age: 17);
var bob = (job: "학생", age: 23);
var charlie = (job: "일반", age: 15);
var dave = (job: "일반", age: 21);
Console.WriteLine($"alice : {GetDiscountRate(alice)}");
Console.WriteLine($"bob : {GetDiscountRate(bob)}");
Console.WriteLine($"charlie : {GetDiscountRate(charlie)}");
Console.WriteLine($"dave : {GetDiscountRate(dave)}");
}
}
}
Comments