Development/C#
[프랙티컬 C# 연습문제] 1부 - 2장
이쥬딩
2023. 7. 14. 22:38
728x90
📍 포인트
-계산 로직을 메서드 형태로 독립 시키기
-메서드의 기능을 단순하게 하기
-클래스 분리하기
-인스턴스 속성이나 인스턴스 필드를 이용하지 않는 메서드는 정적 메서드 변경
-클래스 안에 있는 모든 멤버가 정적 멤버일 경우 정적 클래스로 변경
-상수는 const로 지정 *private OK public read only
-var 사용
-클래스 대신 인터페이스 사용
문제 2.1
Program.cs
using System;
using System.Collections.Generic;
namespace helloworld
{
class Program
{
static void Main(string[] args)
{
var songs = new List<Song>();
var song1 = new Song("song1", "J", 700);
var song2 = new Song("song2", "A", 1000);
var song3 = new Song("song3", "B", 1400);
songs.Add(song1);
songs.Add(song2);
songs.Add(song3);
foreach (var song in songs)
{
Console.WriteLine("{0}, {1}, {2}", song.Title, song.ArtistName, TimeSpan.FromSeconds(song.Length).ToString(@"mm\:ss"));
}
}
}
}
Song.cs
public class Song
{
public string Title { get; set; }
public string ArtistName { get; set; }
public int Length { get; set; }
public Song(string title, string artisName, int length)
{
this.Title = title;
this.ArtistName = artisName;
this.Length = length;
}
}
문제 2.2
Program.cs
using System;
namespace helloworld
{
class Program
{
static void Main(string[] args)
{
PrintInchtoMeter(1, 10);
}
static void PrintInchtoMeter(int start, int stop)
{
for (var inch = start; inch <= stop; inch++)
{
Console.WriteLine("{0} inch = {1:0.0000} m", inch, InchConverter.InchtoMeter(inch));
}
}
}
}
InchConverter.cs
public static class InchConverter
{
private const double ratio = 0.0254;
public static double InchtoMeter(int inch)
{
return inch * ratio;
}
}
문제 2.3
Program.cs
using System;
namespace helloworld
{
class Program
{
static void Main(string[] args)
{
var sales = new SalesCounter("sales.csv");
var amountPerstore = sales.GetPerStoreSales();
foreach (var obj in amountPerstore)
{
Console.WriteLine("{0} {1}", obj.Key, obj.Value);
}
}
}
}
SalesCounter.cs
using System.Collections.Generic;
using System.IO;
public class SalesCounter
{
private IEnumerable<Sale> _sales;
public SalesCounter(string filePath)
{
_sales = ReadSales(filePath);
}
public IDictionary<string, int> GetPerStoreSales()
{
var dict = new SortedDictionary<string, int>();
foreach (Sale sale in _sales)
{
if (dict.ContainsKey(sale.ProductCategory))
dict[sale.ProductCategory] += sale.Amount;
else
dict[sale.ProductCategory] = sale.Amount;
}
return dict;
}
private static IEnumerable<Sale> ReadSales(string filePath)
{
var saless = new List<Sale>();
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
string[] items = line.Split(',');
Sale sale = new Sale
{
ShopName = items[0],
ProductCategory = items[1],
Amount = int.Parse(items[2])
};
saless.Add(sale);
}
return saless;
}
}
728x90