[C# ์ด๋ณด ๊ฐ์ข] ์์ ๋ก ๋ฐฐ์ฐ๋ C# 01
์ ์ฒด์ ์ธ ๊ตฌ์กฐ๋
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
Console.WriteLine(args.Length);
}
}
}
using ~: Java์์ import ํ๋ ๊ฒ๊ณผ ๋์ผ
namespace: Java์ ํจํค์ง์ ๋น์ทํ ์ญํ ์
static void Main(string[] args): Java์ main๋ฉ์๋์ ๋์ผ
์ฌ๊ธฐ์ args.Length๋ ๋ค์ด์ค๋ ๋ฌธ์์ด์ ๊ฐ์๋ฅผ ๋งํ๋๋ฐ, cmd์์ ํ์ธํด๋ณผ ์ ์๋ค.
args์ ๋ฌธ์๊ฐ ๋ค์ด์ค๋ ๊ฒ์ ํ์ธํด๋ณด๊ณ ์ถ์ผ๋ฉด,
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
Console.WriteLine(args.Length);
Console.WriteLine("Hello " + args[0]); //์ถ๊ฐ: ๋ค์ด์ค๋ ๋ฌธ์์ด์ ์ฒซ๋ฒ์งธ๋ง ์ถ๋ ฅ
}
}
}
๋น๋ -> ์๋ฃจ์ ๋น๋๋ฅผ ํ ํ ์ธ์๋ฅผ ๋ถ์ฌ์ฃผ๋ฉด,
์์ ๊ฐ์ด ์ ์ถ๋ ฅ๋๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.
๊ทธ๋ ๋ค๋ฉด args์ int์ธ 1์ ๋ฃ์ด๋ ์ ์ถ๋ ฅ์ด ๋๋์ง ๊ถ๊ธํด์ ธ์ (String ํ์ ์ผ๋ก ๋ฐ์ ๊ฑฐ๋ผ๊ณ ์์ํ๊ธด ํ์ง๋ง) ํด๋ณด์๋๋ฐ,
1์ ๋ฐ์ดํฐ ํ์ ์ ํ์ธํ๊ณ ์ถ์ด์ ์ฝ๋๋ฅผ ์ถ๊ฐํ์๋ค.
// args[0]์ ๋ฐ์ดํฐ ํ์
ํ์ธํ๊ธฐ
if (args[0].GetType() == typeof(string))
{
Console.WriteLine("args[0] is of type string.");
}
else if (args[0].GetType() == typeof(int))
{
Console.WriteLine("args[0] is of type int.");
}
else
{
Console.WriteLine("args[0] is of an unknown type.");
}
์ญ์๋ string์ผ๋ก ๋ฐ์์ง๋ค.
๊ทผ๋ฐ ์ด ์ฝ๋๋ args๊ฐ ๋ฐ๋ ์ธ์๊ฐ ์๋ ๊ฒฝ์ฐ, ์ฆ length๊ฐ 0์ธ ๊ฒฝ์ฐ ์๋ฌ๊ฐ ๋๋ค.
์ด๋ฅผ ์์ธ ์ฒ๋ฆฌ๋ฅผ ํด์ฃผ๋ฉด ์ฝ๋๋ ์๋์ ๊ฐ์์ง๊ณ ,
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
Console.WriteLine(args.Length);
if (args.Length > 0)
{
Console.WriteLine("Hello " + args[0]);
// Check the type of args[0]
if (args[0].GetType() == typeof(string))
{
Console.WriteLine("args[0] is of type string.");
}
else if (args[0].GetType() == typeof(int))
{
Console.WriteLine("args[0] is of type int.");
}
else
{
Console.WriteLine("args[0] is of an unknown type.");
}
}
else
{
Console.WriteLine("No command-line arguments provided.");
}
}
}
}
์คํ์ ํ๋ฉด ์ ์๋์ ํ๋ค.
๊ทผ๋ฐ ๋ฌธ๋ ๋ฐ๋ ์ธ์ ํ์ ์ int๋ก ๋ฐ๊พธ๋ฉด ๋์ง ์์๊น ํ๋ ์๊ฐ์ด ๋ค์๋๋ฐ, ์ฐพ์๋ณด๋ C# ํ๋ก๊ทธ๋จ์ ๋ช ๋ น์ค์์ ์คํ๋ ๋ ์ธ์๋ค์ด ๋ฌธ์์ด ๋ฐฐ์ด๋ก ์ ๋ฌ๋๋ค๊ณ ํ๋ค. ๋ฐ๋ผ์ Main ๋ฉ์๋์ ํ๋ผ๋ฏธํฐ๋ฅผ int[] args๋ก ๋ฐ๊พธ๋ฉด, ์ผ๋ฐ์ ์ธ ๋ฐฉ์์ผ๋ก๋ ํ๋ก๊ทธ๋จ์ด ์คํ๋์ง ์๋๋ค. (Java๋ ๋ง์ฐฌ๊ฐ์ง)
'๐ฅ๏ธ > C#' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C#] c# ๊ณ์ฐ๊ธฐ ๋ง๋ค๊ธฐ (0) | 2023.07.29 |
---|---|
[C#] ์์ ๋ก ๋ฐฐ์ฐ๋ C# 02~04: ๊ฐ๋จํ ๊ณ์ฐ๊ธฐ ๊ตฌํํ๊ธฐ (0) | 2023.07.28 |
[C#] VS code์ c#ํ๊ฒฝ ์ธํ ํ๊ธฐ (0) | 2023.07.26 |
[C#] WPF์ ๋ํ ์ ๋ง ๊ฐ๋จํ ๊ฐ๋ (0) | 2023.07.24 |
[C#] C#๊ณผ .NET Framework์ ๋ํ ์ ๋ง ๊ฐ๋จํ ๊ฐ๋ (0) | 2023.07.24 |