C Sharp - Sizuha/devdog GitHub Wiki

๊ธฐ๋ณธ์ ์œผ๋กœ C++๊ณผ ๋น„์Šทํ•˜๋ฏ€๋กœ, ์—ฌ๊ธฐ์„œ๋Š” C#์—์„œ์˜ ์ฐจ์ด์ ๋งŒ ์„ค๋ช…ํ•จ.

๊ธฐ๋ณธ ๋ฌธ๋ฒ•

C# ๋ฌธ๋ฒ• ์ฐธ์กฐ.

์‚ฝ์งˆ

๋ถ€๋“ฑํ˜ธ ๊ด„ํ˜ธ ์ฃผ์˜

public class DirFlags {
	public bool up;
	public bool down;
	public bool left;
	public bool right;
	
	public DirFlags(bool u=false, bool d=false, bool l=false, bool r=false) {
		up = u;
		down = d;
		left = l;
		right = r;
	}
}

// p2 ->  p1
public DirFlags GetMoveDir() {
	Vector3 p1;
	Vector3 p2;
	GetLastVectors(out p1, out p2);
	
	return new DirFlags(p1.y > p2.y, p1.y < p2.y, p1.x < p2.x, p1.x > p2.x );
}

์ด ์ฝ”๋“œ๋Š” ์ปดํŒŒ์ผ ์˜ค๋ฅ˜๊ฐ€ ๋‚œ๋‹ค.

๋‹ค์Œ ๋ถ€๋ถ„์„ ์ œ๋„ˆ๋ฆญ ๋ฌธ๋ฒ•์œผ๋กœ ์ธ์‹ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

p1.x < p2.x, p1.x > p2.x

์ด ์˜ค๋ฅ˜๋ฅผ ํ”ผํ•˜๋ ค๋ฉด, ํŒŒ๋ผ๋งคํ„ฐ๋ฅผ ๊ฐ๊ฐ ๋”ฐ๋กœ๋”ฐ๋กœ ๋ณ€์ˆ˜์— ๋‹ด๊ฑฐ๋‚˜, ๊ด„ํ˜ธ๋ฅผ ๋ฌถ์–ด์„œ ์ปดํŒŒ์ผ๋Ÿฌ์—๊ฒŒ ๋ฌธ๋ฒ•์˜ ์šฐ์„ ์ˆœ์œ„๋ฅผ ์ง€์ •ํ•ด ์ค„ ์ˆ˜ ๋ฐ–์— ์—†๋‹ค.

Out/Ref Parameter ์ œ์•ฝ

IEnumerator๊ฐ™์€ iterator ์†์„ฑ์„ ๊ฐ€์ง„ ๋งค์†Œ๋“œ์—์„œ๋Š” out/ref ํŒŒ๋ผ๋งคํ„ฐ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.

Tips

enum ํƒ€์ž…์˜ ๊ฐ’/์ด๋ฆ„ ํƒ์ƒ‰

System.Enum ํด๋ž˜์Šค์˜ static ๋งค์„œ๋“œ๋ฅผ ํ™œ์šฉํ•˜๋ฉด, enum์œผ๋กœ ์ •์˜๋œ ํƒ€์ž…์ด ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๊ฐ’ ํ˜น์€ ์ด๋ฆ„๋“ค์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. ๋ฌผ๋ก  ๊ทธ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ†ตํ•ด์„œ foreach๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ๋„ ๊ฐ€๋Šฅ.

public enum Suits
{
    Spades,
    Hearts,
    Clubs,
    Diamonds,
    NumSuits
}

public void PrintAllSuits()
{
    foreach (var suit in System.Enum.GetValues(typeof(Suits)))
    {
        System.Console.WriteLine(suit.ToString());
    }
}

๋‚ ์งœ/์‹œ๊ฐ„

Unix TimeStamp์™€ DateTime ์‚ฌ์ด์˜ ํ˜• ๋ณ€ํ™˜

private static readonly DateTime UnixEpoch =
    new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public static long GetCurrentUnixTimestampMillis()
{
    return (long) (DateTime.UtcNow - UnixEpoch).TotalMilliseconds;
}

public static DateTime DateTimeFromUnixTimestampMillis(long millis)
{
    return UnixEpoch.AddMilliseconds(millis);
}

public static long GetCurrentUnixTimestampSeconds()
{
    return (long) (DateTime.UtcNow - UnixEpoch).TotalSeconds;
}

public static DateTime DateTimeFromUnixTimestampSeconds(long seconds)
{
    return UnixEpoch.AddSeconds(seconds);
}

DateTime(UTC)๋ฅผ ์ง€์—ญ ์‹œ๊ฐ„๋Œ€๋กœ ๋ณ€ํ™˜

DateTime local = (DateTime_Object).ToLocalTime();

IO

ํŒŒ์ผ/๋””๋ ‰ํ† ๋ฆฌ ํƒ์ƒ‰

DirectoryInfo root = new DirectoryInfo(path);
FileInfo[] files = root.GetFiles("*.xxx");

foreach (FileInfo f in files) {
	StreamReader input = f.OpenText();
	// . . .
}

ํŒŒ์ผ/๋””๋ ‰ํ† ๋ฆฌ ๊ด€๋ฆฌ

์กด์žฌ ์—ฌ๋ถ€ ํ™•์ธ

bool is_file_exist = System.IO.File.Exists(file_path);
bool is_dir_exist = System.IO.Directory.Exists(path);

๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ

Directory.CreateDirectory("path");

Path์ƒ์˜ ๋ชจ๋“  ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

๋””๋ ‰ํ† ๋ฆฌ ์‚ญ์ œ

System.IO.Directory.Delete(path); 
System.IO.Directory.Delete(path, true); // ์ด ๊ฒฝ์šฐ, ์„œ๋ธŒ ๋””๋ ‰ํ† ๋ฆฌ๊นŒ์ง€ ์ง€์›€.

TextFile

ํ…์ŠคํŠธ ํŒŒ์ผ ์ „์ฒด๋ฅผ ์ฝ์–ด์˜ค๊ฑฐ๋‚˜, ๋ฌธ์ž์—ด ์ „์ฒด๋ฅผ ํ…์ŠคํŠธ ํŒŒ์ผ๋กœ ์ €์žฅํ•˜๊ณ ์ž ํ•  ๋•Œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ฐ„๋‹จํžˆ ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅ.

using System.IO;

// ์ด๋ฏธ ํŒŒ์ผ์ด ์กด์žฌํ•  ๊ฒฝ์šฐ์—๋Š” ๊ธฐ์กด ํŒŒ์ผ์˜ ๋‚ด์šฉ์€ ์ง€์›Œ์ง€๊ณ  ์ƒˆ๋กœ์šด ๋‚ด์šฉ์œผ๋กœ ๋ฎ์–ด์“ฐ๊ฒŒ ๋œ๋‹ค.
File.WriteAllText(path, createText);

File.ReadAllText(path);

ํ…์ŠคํŠธ ํŒŒ์ผ ์ƒ์„ฑ/์“ฐ๊ธฐ

using System.IO;

StreamWriter sw = File.CreateText(path);
sw.WriteLine("test");
sw.Close();

File.CreateText()๋Š” append ๋ชจ๋“œ๊ฐ€ false๋กœ ์„ค์ •๋œ StreamWrite๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. ๋”ฐ๋ผ์„œ, ์ด๋ฏธ ํŒŒ์ผ์ด ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” ๋ฎ์–ด ์“ฐ๊ธฐ๋ฅผ ํ•˜๊ฒŒ ๋œ๋‹ค. Encoding์€ UTF-8๋กœ ์„ค์ •๋œ๋‹ค.

ํ…์ŠคํŠธ ํŒŒ์ผ ์—ด๊ธฐ/์ฝ๊ธฐ

using System.IO;

StreamReader sr = File.OpenText(path);
string s = sr.ReadLine();

Path

using System.IO;

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileNameWithoutExtension(fileName);
Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'", fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", path, result);

// This code produces output similar to the following: 
// 
// GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile' 
// GetFileName('C:\mydir\') returns ''

XML

XmlTextReader

using System.Xml;

XmlTextReader reader = new XmlTextReader("books.xml");

while (reader.Read()) {
	switch (reader.NodeType) {
	case XmlNodeType.Element: // The node is an element.
		Console.Write("<" + reader.Name);
		Console.WriteLine(">");
		break;
	case XmlNodeType.Text: //Display the text in each element.
		Console.WriteLine (reader.Value);
		break;
	case XmlNodeType. EndElement: //Display the end of the element.
		Console.Write("</" + reader.Name);
		Console.WriteLine(">");
		break;
	}

	// Read attributes.
	if (reader.HasAttributes) {
		Console.WriteLine("Attributes of <" + reader.Name + ">");
		while (reader.MoveToNextAttribute()) {
			Console.WriteLine(" {0}={1}", reader.Name, reader.Value);
		}
		// Move the reader back to the element node.
		reader.MoveToElement();
	}
}

reader.Close();

DOM Parser

using System.Xml;

XmlTextReader reader = new XmlTextReader("patch_list.xml");

XmlDocument xml = new XmlDocument ();
xml.Load(reader);
XmlElement xmlRoot = xml.DocumentElement;

// Root
foreach (XmlNode node in xmlRoot.ChildNodes) {
	string nodeName = node.Name;
	XmlAttribute attr = node.Attributes["Attribute Name"].Value; // ์†์„ฑ๊ฐ’ ๊ฐ€์ ธ์˜ค๊ธฐ.

	string value = node.value; // <node>value</node> ํ˜•ํƒœ์ธ ๊ฒฝ์šฐ.
	string innerText = node.InnerText; // value ๋ถ€๋ถ„์ด ์—ฌ๋Ÿฌํ–‰์œผ๋กœ ๋˜์–ด ์žˆ๋Š” ๊ฒฝ์šฐ.
}

reader.Close();

Using LINQ-to-XML

Using LINQ-to-XML, you can do var doc = XDocument.Load("yourfilepath"). From there its just a matter of querying the data you want, say like this:

var authors = doc.Root.Elements().Select( x => x.Element("Author") );
using System;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main( string[] args )
        {
            XDocument doc = XDocument.Load( "XMLFile1.xml" );

            var authors = doc.Descendants( "Author" );

            foreach ( var author in authors )
            {
                Console.WriteLine( author.Value );
            }
            Console.ReadLine();
        }
    }
}

Network

http://stackoverflow.com/questions/4015324/http-request-with-post

using System.Net;
using System.Collections.Specialized;

// POST
using (var client = new WebClient())
{
    var values = new NameValueCollection();
    values["thing1"] = "hello";
    values["thing2"] = "world";

    var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);

    var responseString = Encoding.Default.GetString(response);
}

// GET
using (var client = new WebClient())
{
    var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}

๋ณด์•ˆ

AES

using System.Security.Cryptography;
using System.Text;
using System;

public class CryptoLib {

	// 128bit(16byte)ใฎIV๏ผˆๅˆๆœŸใƒ™ใ‚ฏใ‚ฟ๏ผ‰ใจKey๏ผˆๆš—ๅทใ‚ญใƒผ๏ผ‰...
	private const string iv = @"1234567890ABCDEF";
	private const string key = @"1234567890ABCDEF";

	/// <summary>
	/// ๆ–‡ๅญ—ๅˆ—ใ‚’AESใงๆš—ๅทๅŒ–.
	/// </summary>
	public static string Encrypt(string text)
	{
		// AESๆš—ๅทๅŒ–ใ‚ตใƒผใƒ“ใ‚นใƒ—ใƒญใƒใ‚คใƒ€.
		AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
		aes.BlockSize = 128;
		aes.KeySize = 128;


		aes.IV = Encoding.UTF8.GetBytes(iv);
		aes.Key = Encoding.UTF8.GetBytes(key);
		aes.Mode = CipherMode.CBC;
		aes.Padding = PaddingMode.PKCS7;
		
		// ๆ–‡ๅญ—ๅˆ—ใ‚’ใƒใ‚คใƒˆๅž‹้…ๅˆ—ใซๅค‰ๆ›.
		byte[] src = Encoding.Unicode.GetBytes(text);
		
		// ๆš—ๅทๅŒ–ใ™ใ‚‹.
		using (ICryptoTransform encrypt = aes.CreateEncryptor())
		{
			byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
			
			// ใƒใ‚คใƒˆๅž‹้…ๅˆ—ใ‹ใ‚‰Base64ๅฝขๅผใฎๆ–‡ๅญ—ๅˆ—ใซๅค‰ๆ›.
			return Convert.ToBase64String(dest);
		}
	}
	
	/// <summary>
	/// ๆ–‡ๅญ—ๅˆ—ใ‚’AESใงๅพฉๅทๅŒ–.
	/// </summary>
	public static string Decrypt(string text)
	{
		// AESๆš—ๅทๅŒ–ใ‚ตใƒผใƒ“ใ‚นใƒ—ใƒญใƒใ‚คใƒ€.
		AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
		aes.BlockSize = 128;
		aes.KeySize = 128;
		aes.IV = Encoding.UTF8.GetBytes(iv);
		aes.Key = Encoding.UTF8.GetBytes(key);
		aes.Mode = CipherMode.CBC;
		aes.Padding = PaddingMode.PKCS7;
		
		// Base64ๅฝขๅผใฎๆ–‡ๅญ—ๅˆ—ใ‹ใ‚‰ใƒใ‚คใƒˆๅž‹้…ๅˆ—ใซๅค‰ๆ›.
		byte[] src = System.Convert.FromBase64String(text);
		
		// ่ค‡ๅทๅŒ–ใ™ใ‚‹.
		using (ICryptoTransform decrypt = aes.CreateDecryptor())
		{
			byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length);
			return Encoding.Unicode.GetString(dest);
		}
	}
}

System / OS

Shell ๋ช…๋ น ์‹คํ–‰

System.Diagnostics.Process.Start("process-name", "parameters");

// ํ”„๋กœ์„ธ์Šค๊ฐ€ ์ข…๋ฃŒ๋  ๋•Œ๊นŒ์ง€ ๋Œ€๊ธฐ
System.Diagnostics.Process.Start("process-name", "parameters").WaitForExit();

LINQ

์ฐธ๊ณ 

IEnumerable<T> ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•œ ๋Œ€์ƒ์— ๋Œ€ํ•ด ์ ์šฉ ๊ฐ€๋Šฅ.

๊ธฐ๋ณธ ์‚ฌ์šฉ๋ฒ•

Query ๋ฌธ๋ฒ• ์ด์šฉ

using System.Linq;

// The Three Parts of a LINQ Query:
//  1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
		
// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery = from num in numbers where (num % 2) == 0 select num;
		
// 3. Query execution.
foreach (int num in numQuery) Console.Write("{0,1} ", num);

Linq ํ•จ์ˆ˜ ์ด์šฉ

using System.Linq;

int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// numQuery is an IEnumerable<int>
var numQuery = numbers.Where(num => num % 2 == 0);
โš ๏ธ **GitHub.com Fallback** โš ๏ธ