2022년 2월 1일 화요일

C# 기본실습문제, 속성, 생성자, StringBuilder

 



C# 기본실습문제, 속성, 생성자, StringBuilder



C# 기본실습문제, 속성, 생성자,StringBuilder1. Sample 클래스는 public Length 속성을 가지고 get, set 접근자를 가지고 있다. 아래 코드중 정상적으로 돟작하는것은? a. Sample.Length = 20; b. Sample m = new Sample(); m.Length = 10; c. Console.WriteLine(S…

ojc.asia



  • 0열 선택0열 다음에 열 추가
  • 0행 선택0행 다음에 행 추가
셀 전체 선택
열 너비 조절
행 높이 조절
C# 기본실습문제, 속성, 생성자, StringBuilder


1. Sample 클래스는 public Length 속성을 가지고 get, set 접근자를 가지고 있다. 아래 코드중 정상적으로 돟작하는것은?


a. Sample.Length = 20;


b. Sample m = new Sample();


m.Length = 10;


c. Console.WriteLine(Sample.Length);


d. Sample m = new Sample();


int len;


len = m.Length;


e. Sample m = new Sample();


m.Length = m.Length + 20;






정답 : b, d, e






2. Sample 클래스의 쓰기전용 일반속성 Length를 구현하세요.(Sample 클래스 작성)


[정답]


class Sample


{


int len;


public int Length


{


set


{


len = value;


}


}


}






3. 괄호를 채우세요.


using System;


class EnumPropertyExam


{


DayOfWeek _day;


public DayOfWeek Day


{


get


{


// 금요일인 경우 예외발생


if ( )


{


throw new Exception("Invalid access");


}


return this._day;


}


set


{


this._day = value;


}


}


}






class Program


{


static void Main()


{


EnumPropertyExam example = new EnumPropertyExam();


example.Day = DayOfWeek.Monday;


Console.WriteLine(example.Day == DayOfWeek.Monday);


example.Day = DayOfWeek.Friday;


Console.WriteLine(example.Day);


}


}


/* 결과 :


True






처리되지 않은 예외: System.Exception: Invalid access


위치: EnumPropertyExam.get_Day() 파일 C:\GitHub\csharp20181230\PropertyTest2\PropertyTest2\Program.cs:줄 12


위치: Program.Main() 파일 C:\GitHub\csharp20181230\PropertyTest2\PropertyTest2\Program.cs:줄 31


*/






//정답 : this._day == DayOfWeek.Friday






4. 사용자로 부터 두수를 입력받아 그사이의 소수의 합을 출력하세요.


using System;




class Program
{
static void Main()
{
int a, b, max, min, i, count, totalsum;


Console.WriteLine("두수를 입력하세요.");
Console.WriteLine("예 : 3,5");
string str = Console.ReadLine();
str.Trim();
string[] strarr = str.Split(',');
if (strarr.Length != 2)
{
Console.WriteLine("숫자2개를 콤마로 구분해서 입력하세요~");
return;
}


a = int.Parse(strarr[0]);
b = int.Parse(strarr[1]);




if (a < b)
{
max = b;
min = a;


}
else
{
max = a;
min = b;
}
i = min;
totalsum = 0;


for (int k = min; k <= max; k++)
{
count = 0;
for (int l = 2; l <= k; l++)
{
if (k % l == 0)
{
count++;
}
}


if (count == 1)
{
totalsum += k;
}
}


Console.WriteLine(totalsum);


}
}








5. 아래 예문에서 기본 생성자를 삭제해도 똑같은 결과를 낼수 있도록 코드를 수정하세요.






using System;






namespace ConstructorTest2


{


class Emp


{


string name;


//기본생성자, new할때 호출, 객체를 초기화


public Emp() {


name = "홍길이";


Console.WriteLine("EMP 객체생성..." + name);


}


public Emp(string name) //생성자, 생성자 오버로딩


{


this.name = name;


Console.WriteLine("EMP 객체생성..." + name);


}


}


class EmpTest


{


static void Main(string[] args)


{


Emp e = new Emp();


Emp e1 = new Emp("광개토");


}


}


}


[정답]


//public Emp(string name = "홍길이")






6. 실행결과를 참조하여 괄호를 채우세요.






using System;






public class Emp


{


( 1 )


}


public class ToStringMethod


{


static void Main()


{


Emp e = new Emp();


( 2 ) o = ( 3 ) ;






Console.WriteLine(o.ToString());


Console.WriteLine(e.ToString());


Console.WriteLine(e);


}


}


//결과


System.Object


This is Emp class


This is Emp class






[정답]


public override string ToString()


{


return "This is Emp class";


}






object


object






7. 1부터 10000까지 7은 모두 몇번 나오는가? C#으로 코딩 하세요.


[정답]


1. Console.WriteLine(Enumerable.Range(1,10000).Sum(o=>o.ToString().Count(n=>n=='7')));






2. public static void searchSeven(int num) {
if (num % 10 == 7) count++;
if (num > 10) searchSeven(num / 10);
}
3. static void Main()
{
Console.WriteLine("숫자를 입력하세요 :");
string str = "";
str = Console.ReadLine();


int m = 0;
bool parsed = Int32.TryParse(str, out m);
if (!parsed)
{
Console.WriteLine("숫자를 입력하세요");
Environment.Exit(0);
}


int input = Convert.ToInt32(str);
int hap = 0; int i = 0; int num = 0;
string Word = "7";
for (i = 1; i <= input; i++)
{
str = Convert.ToString(i);
num = str.Length - str.Replace(Word, "").Length;
hap = hap + num;
}
Console.WriteLine("7의 총 개수: {0}", hap);
}






8. c:\GitHub 폴더에 number.txt 파일을 만들고 숫자를 1부터 100까지를 한라인씩


100줄에 입략한 후 이를 C# 응용프로그램에서 읽어서 합을 구하세요.






[정답]


using System;
using System.IO;
namespace ReadLineFromFile{
class Program {
static void Main(string[] args)
{
int sum = Sum(@"c:\GitHub\number.txt");
Console.WriteLine($"{sum}");
}
static int Sum( string file )
{
int sum = 0;
string[] arr = File.ReadAllLines(file);
foreach (string s in arr) sum += Int32.Parse(s);
return sum;
}
}
}






9. String과 StringBuilder의 차이점에 대해 설명하고 예제를 작성하세요.


[정답]


String은 Immutable 즉 한번 문자열을 지정하고 객체를 생성했으면, 더이상 문자열을 수정할 수 없게 된다. Mutable 타입인 StringBuilder는 이와 반대의 경우로 객체 생성이후에도 문자열을 수정할 수 있다.






예를 들어, 아래의 코드는 1부터 10000까지 숫자를 string 변수에 연속해서 추가하는 예이다.






string s = string.Empty;


for(int i=1; i<=10000; i++)


{


s += i.ToString();


}


이 코드의 문제점은 string변수 s에 숫자를 추가할 때, 해당 변수 s의 값을 수정하는 것이 아니라 별도의 새 string객체를 만들고(물론 이름은 s로 똑같지만 Heap상의 메모리는 다르다) 이전 s의 문자값을 새로운 문자열 객체에 복사하게 된다는 점이다. 이러한 새 객체 생성및 기존 데이타 복사가 루프에서 만번 일어 나기 때문에 성능은 저하되고 필요 이상의 많은 메모리를 쓰게 된다.






이러한 문제점을 막기 위해 string 대신 StringBuilder를 사용한다. StringBuilder는 새로운 객체를 생성하지 않고 자신의 내부 버퍼 값만 변경함으로써 값을 추가하게 된다. 따라서 불필요한 객체 생성과 매번 일어나는 데이타 복사 과정이 없어지게 된다. (주: StringBuilder도 해당 객체의 버퍼 용량(Capacity)을 넘는 데이타가 들어올 경우 새로운 버퍼를 현재 Capacity의 2개 크기로 재할당하고 기존 데이타를 복사하게 된다.)






StringBuilder sb = new StringBuilder();


for (int i = 1; i <= 10000; i++)


{


sb.Append(i);


}


string s = sb.ToString();






10. 문자배열에서 중복되지 않는 첫 문자를 리턴하는 함수를 작성하시오. 예를 들어, 입력 문자배열이 abcabdefe 일 때, 중복되지 않는 첫 문자 c 를 리턴함.


[정답]


1.


void RunTest()


{


string s = "abcabdefe";


char ch = GetFirstChar(s.ToCharArray());


Console.WriteLine(ch);


}






char GetFirstChar(char[] S)


{


Dictionary<char, int=""> ht = new Dictionary<char, int="">();</char,></char,>






foreach (char ch in S)


{


if (!ht.ContainsKey(ch))


ht[ch] = 1;


else


ht[ch] += 1;


}






foreach (char ch in S)


{


if (ht[ch] == 1)


return ch;


}






return '\0';


}






2.






using System;


namespace DupTest
{
class Program {
static void Main(string[] args)
{
string s = "abcababcd";
Console.WriteLine(DupCheck(s));
}
static char DupCheck(string s)
{
int cnt;
for (int i = 0; i < s.Length; i++)
{
cnt = CharCnt(s, s[i]);
if (cnt == 1) return s[i];
}
return '\0';
}
static int CharCnt(string s, char c)
{
string[] StringArray = s.Split(new char[] { c }, StringSplitOptions.None);
return StringArray.Length - 1;
}
}
}




3. string inStr1 = "abcabdefe";
char[] Array = inStr1.ToCharArray();
string result = "";
for (int i = 0; i < inStr1.Length; i++)
{
if (inStr1.Length - inStr1.Replace(Array[i].ToString(), "").Length == 1)
{
result = Array[i].ToString();
i = inStr1.Length - 1;
}
}
Console.WriteLine(result);














  • 셀 병합
  • 행 분할
  • 열 분할
  • 너비 맞춤
  • 삭제




http://ojc.asia/bbs/board.php?bo_table=LecCsharp&wr_id=406


C# 기본실습문제, 속성, 생성자, StringBuilder

C# 기본실습문제, 속성, 생성자,StringBuilder1. Sample 클래스는 public Length 속성을 가지고 get, set 접근자를 가지고 있다. 아래 코드중 정상적으로 돟작하는것은? a. Sample.Length = 20; b. Sample m = new Sample(); m

ojc.asia


C# 기본실습문제, 속성, 생성자,StringBuilder1. Sample 클래스는 public Length 속성을 가지고 get, set 접근자를 가지고 있다. 아래 코드중 정상적으로 돟작하는것은? a. Sample.Length = 20; b. Sample m = new Sample(); m.Length = 10; c. Console.WriteLine(S…

ojc.asia



  • 0열 선택0열 다음에 열 추가
  • 0행 선택0행 다음에 행 추가
셀 전체 선택
열 너비 조절
행 높이 조절
C# 기본실습문제, 속성, 생성자, StringBuilder


1. Sample 클래스는 public Length 속성을 가지고 get, set 접근자를 가지고 있다. 아래 코드중 정상적으로 돟작하는것은?


a. Sample.Length = 20;


b. Sample m = new Sample();


m.Length = 10;


c. Console.WriteLine(Sample.Length);


d. Sample m = new Sample();


int len;


len = m.Length;


e. Sample m = new Sample();


m.Length = m.Length + 20;






정답 : b, d, e






2. Sample 클래스의 쓰기전용 일반속성 Length를 구현하세요.(Sample 클래스 작성)


[정답]


class Sample


{


int len;


public int Length


{


set


{


len = value;


}


}


}






3. 괄호를 채우세요.


using System;


class EnumPropertyExam


{


DayOfWeek _day;


public DayOfWeek Day


{


get


{


// 금요일인 경우 예외발생


if ( )


{


throw new Exception("Invalid access");


}


return this._day;


}


set


{


this._day = value;


}


}


}






class Program


{


static void Main()


{


EnumPropertyExam example = new EnumPropertyExam();


example.Day = DayOfWeek.Monday;


Console.WriteLine(example.Day == DayOfWeek.Monday);


example.Day = DayOfWeek.Friday;


Console.WriteLine(example.Day);


}


}


/* 결과 :


True






처리되지 않은 예외: System.Exception: Invalid access


위치: EnumPropertyExam.get_Day() 파일 C:\GitHub\csharp20181230\PropertyTest2\PropertyTest2\Program.cs:줄 12


위치: Program.Main() 파일 C:\GitHub\csharp20181230\PropertyTest2\PropertyTest2\Program.cs:줄 31


*/






//정답 : this._day == DayOfWeek.Friday






4. 사용자로 부터 두수를 입력받아 그사이의 소수의 합을 출력하세요.


using System;




class Program
{
static void Main()
{
int a, b, max, min, i, count, totalsum;


Console.WriteLine("두수를 입력하세요.");
Console.WriteLine("예 : 3,5");
string str = Console.ReadLine();
str.Trim();
string[] strarr = str.Split(',');
if (strarr.Length != 2)
{
Console.WriteLine("숫자2개를 콤마로 구분해서 입력하세요~");
return;
}


a = int.Parse(strarr[0]);
b = int.Parse(strarr[1]);




if (a < b)
{
max = b;
min = a;


}
else
{
max = a;
min = b;
}
i = min;
totalsum = 0;


for (int k = min; k <= max; k++)
{
count = 0;
for (int l = 2; l <= k; l++)
{
if (k % l == 0)
{
count++;
}
}


if (count == 1)
{
totalsum += k;
}
}


Console.WriteLine(totalsum);


}
}








5. 아래 예문에서 기본 생성자를 삭제해도 똑같은 결과를 낼수 있도록 코드를 수정하세요.






using System;






namespace ConstructorTest2


{


class Emp


{


string name;


//기본생성자, new할때 호출, 객체를 초기화


public Emp() {


name = "홍길이";


Console.WriteLine("EMP 객체생성..." + name);


}


public Emp(string name) //생성자, 생성자 오버로딩


{


this.name = name;


Console.WriteLine("EMP 객체생성..." + name);


}


}


class EmpTest


{


static void Main(string[] args)


{


Emp e = new Emp();


Emp e1 = new Emp("광개토");


}


}


}


[정답]


//public Emp(string name = "홍길이")






6. 실행결과를 참조하여 괄호를 채우세요.






using System;






public class Emp


{


( 1 )


}


public class ToStringMethod


{


static void Main()


{


Emp e = new Emp();


( 2 ) o = ( 3 ) ;






Console.WriteLine(o.ToString());


Console.WriteLine(e.ToString());


Console.WriteLine(e);


}


}


//결과


System.Object


This is Emp class


This is Emp class






[정답]


public override string ToString()


{


return "This is Emp class";


}






object


object






7. 1부터 10000까지 7은 모두 몇번 나오는가? C#으로 코딩 하세요.


[정답]


1. Console.WriteLine(Enumerable.Range(1,10000).Sum(o=>o.ToString().Count(n=>n=='7')));






2. public static void searchSeven(int num) {
if (num % 10 == 7) count++;
if (num > 10) searchSeven(num / 10);
}
3. static void Main()
{
Console.WriteLine("숫자를 입력하세요 :");
string str = "";
str = Console.ReadLine();


int m = 0;
bool parsed = Int32.TryParse(str, out m);
if (!parsed)
{
Console.WriteLine("숫자를 입력하세요");
Environment.Exit(0);
}


int input = Convert.ToInt32(str);
int hap = 0; int i = 0; int num = 0;
string Word = "7";
for (i = 1; i <= input; i++)
{
str = Convert.ToString(i);
num = str.Length - str.Replace(Word, "").Length;
hap = hap + num;
}
Console.WriteLine("7의 총 개수: {0}", hap);
}






8. c:\GitHub 폴더에 number.txt 파일을 만들고 숫자를 1부터 100까지를 한라인씩


100줄에 입략한 후 이를 C# 응용프로그램에서 읽어서 합을 구하세요.






[정답]


using System;
using System.IO;
namespace ReadLineFromFile{
class Program {
static void Main(string[] args)
{
int sum = Sum(@"c:\GitHub\number.txt");
Console.WriteLine($"{sum}");
}
static int Sum( string file )
{
int sum = 0;
string[] arr = File.ReadAllLines(file);
foreach (string s in arr) sum += Int32.Parse(s);
return sum;
}
}
}






9. String과 StringBuilder의 차이점에 대해 설명하고 예제를 작성하세요.


[정답]


String은 Immutable 즉 한번 문자열을 지정하고 객체를 생성했으면, 더이상 문자열을 수정할 수 없게 된다. Mutable 타입인 StringBuilder는 이와 반대의 경우로 객체 생성이후에도 문자열을 수정할 수 있다.






예를 들어, 아래의 코드는 1부터 10000까지 숫자를 string 변수에 연속해서 추가하는 예이다.






string s = string.Empty;


for(int i=1; i<=10000; i++)


{


s += i.ToString();


}


이 코드의 문제점은 string변수 s에 숫자를 추가할 때, 해당 변수 s의 값을 수정하는 것이 아니라 별도의 새 string객체를 만들고(물론 이름은 s로 똑같지만 Heap상의 메모리는 다르다) 이전 s의 문자값을 새로운 문자열 객체에 복사하게 된다는 점이다. 이러한 새 객체 생성및 기존 데이타 복사가 루프에서 만번 일어 나기 때문에 성능은 저하되고 필요 이상의 많은 메모리를 쓰게 된다.






이러한 문제점을 막기 위해 string 대신 StringBuilder를 사용한다. StringBuilder는 새로운 객체를 생성하지 않고 자신의 내부 버퍼 값만 변경함으로써 값을 추가하게 된다. 따라서 불필요한 객체 생성과 매번 일어나는 데이타 복사 과정이 없어지게 된다. (주: StringBuilder도 해당 객체의 버퍼 용량(Capacity)을 넘는 데이타가 들어올 경우 새로운 버퍼를 현재 Capacity의 2개 크기로 재할당하고 기존 데이타를 복사하게 된다.)






StringBuilder sb = new StringBuilder();


for (int i = 1; i <= 10000; i++)


{


sb.Append(i);


}


string s = sb.ToString();






10. 문자배열에서 중복되지 않는 첫 문자를 리턴하는 함수를 작성하시오. 예를 들어, 입력 문자배열이 abcabdefe 일 때, 중복되지 않는 첫 문자 c 를 리턴함.


[정답]


1.


void RunTest()


{


string s = "abcabdefe";


char ch = GetFirstChar(s.ToCharArray());


Console.WriteLine(ch);


}






char GetFirstChar(char[] S)


{


Dictionary<char, int=""> ht = new Dictionary<char, int="">();</char,></char,>






foreach (char ch in S)


{


if (!ht.ContainsKey(ch))


ht[ch] = 1;


else


ht[ch] += 1;


}






foreach (char ch in S)


{


if (ht[ch] == 1)


return ch;


}






return '\0';


}






2.






using System;


namespace DupTest
{
class Program {
static void Main(string[] args)
{
string s = "abcababcd";
Console.WriteLine(DupCheck(s));
}
static char DupCheck(string s)
{
int cnt;
for (int i = 0; i < s.Length; i++)
{
cnt = CharCnt(s, s[i]);
if (cnt == 1) return s[i];
}
return '\0';
}
static int CharCnt(string s, char c)
{
string[] StringArray = s.Split(new char[] { c }, StringSplitOptions.None);
return StringArray.Length - 1;
}
}
}




3. string inStr1 = "abcabdefe";
char[] Array = inStr1.ToCharArray();
string result = "";
for (int i = 0; i < inStr1.Length; i++)
{
if (inStr1.Length - inStr1.Replace(Array[i].ToString(), "").Length == 1)
{
result = Array[i].ToString();
i = inStr1.Length - 1;
}
}
Console.WriteLine(result);














  • 셀 병합
  • 행 분할
  • 열 분할
  • 너비 맞춤
  • 삭제




(동영상)C#기본실습문제, 인덱서, 이벤트, 델리게이트, 속성, 어트리뷰트, 봉인클래스, REF, OUT, Partial Class, C#교육, C#학원, 닷넨ㅅ학원, 닷넷교육, 자바학원, 자바교육

 (동영상)C#기본실습문제, 인덱서, 이벤트, 델리게이트, 속성, 어트리뷰트, 봉인클래스, REF, OUT, Partial Class, C#교육, C#학원, 닷넨ㅅ학원, 닷넷교육, 자바학원, 자바교육


http://ojc.asia/bbs/board.php?bo_table=LecCsharp&wr_id=407 


C#기본실습, 인덱서, 이벤트, 델리게이트, 속성, 어트리뷰트

C#기본실습, 인덱서, 이벤트, 델리게이트, 속성, 어트리뷰트1. (델리게이트)실행 결과를 참조하여 괄호를 채우세요. [결과] Static method: 10 My instance: 5 using System; public delegate string FirstDelegate(int x); cla

ojc.asia

https://www.youtube.com/watch?v=QXyOvFGp-rE&list=PLxU-iZCqT52DJyR6gqJy0MCL8RiTVXdos&index=16 


https://www.youtube.com/watch?v=RWrdG2lfnBA&list=PLxU-iZCqT52DJyR6gqJy0MCL8RiTVXdos&index=15 

C#기본실습, 인덱서, 이벤트, 델리게이트, 속성, 어트리뷰트 

 

1. (델리게이트)실행 결과를 참조하여 괄호를 채우세요.


[결과]


Static method: 10

My instance: 5 

 


using System;


public delegate string FirstDelegate(int x);

class DelegateTest

{

    string name;

 

    static void Main()

   {

        FirstDelegate d1 = (  괄호를 채우세요 );

 

        DelegateTest instance = new DelegateTest();

        instance.name = "My instance";

        FirstDelegate d2 = ( 괄호를 채우세요 );

 

        Console.WriteLine(d1(10)); // Writes out "Static method: 10"

        Console.WriteLine( 괄호를 채우세요 );  // Writes out "My instance: 5"

    }

 

    static string StaticMethod(int i)

   {

        return (  괄호를 채우세요 );

    }

 

    string InstanceMethod(int i)

    {

        return string.Format("{0}: {1}", name, i);

    }

}


[정답]

StaticMethod

instance.InstanceMethod

d2(5)

string.Format("Static method: {0}", i);



2. (델리게이트)아래는 다이렉트로 메소드를 호출하는 예제 입니다.

   델리게이트를 이용하여 두가지 형태로 재작성 바랍니다.

   -. 델리게이트를 별도로 선언하여

   -. Action 델리게이트를 이용하여 


using System;



namespace Akadia.NoDelegate

{

    public class MyClass

    {

        public void Process()

        {

            Console.WriteLine("Process() begin");

            Console.WriteLine("Process() end");

        }

    }

 

    public class Test

    {

        static void Main(string[] args)

        {

            MyClass myClass = new MyClass();

            myClass.Process();

        }

    }

}


[정답]

5-1.


using System;


namespace Akadia.NoDelegate {


  public delegate void Process();

  

  public class MyClass {

    public void Process() {

      Console.WriteLine("Process() begin");

      Console.WriteLine("Process() end");

    }

  }


  public class Test {

    static void Main(string[] args) {

      Process process = new MyClass().Process;

      process();

    }

  }

}

 


   5-2.


using System;


namespace Akadia.NoDelegate {

  public class MyClass {

    public void Process() {

      Console.WriteLine("Process() begin");

      Console.WriteLine("Process() end");

    }

  }


  public class Test {

    static void Main(string[] args) {

      Action process = new MyClass().Process;

      process();

    }

  }

}



3. (델리게이트)실행 결과를 참조하여 괄호를 채우세요.


결과 : 

[c:\GitHub\process.log 파일의 내용]

Process() begin

Process() end



using System;

using System.IO;



namespace Akadia.SimpleDelegate

{

    public class MyClass

    {

        public delegate void LogHandler(string message);

        public void Process(LogHandler logHandler)

        {

            (  채워 주세요...)

        }

    }

   

    public class FileLogger

    {

        FileStream fileStream;

        StreamWriter streamWriter;

 

        // Constructor

        public FileLogger(string filename)

        {

            fileStream = new FileStream(filename, FileMode.Create);

            streamWriter = new StreamWriter(fileStream);

        }

 

        // Member Function which is used in the Delegate

        public void Logger(string s)

        {

            streamWriter.WriteLine(s);

        }

 

        public void Close()

        {

            streamWriter.Close();

            fileStream.Close();

        }

    }

 

    public class TestApplication

    {

        static void Main(string[] args)

        {

            FileLogger fl = new FileLogger("c:\\GitHub\\process.log");

 

            MyClass myClass = new MyClass();

 

            MyClass.LogHandler myLogger = ( 채워 주세요 );

            ( 채워 주세요  )

            fl.Close();

        }

    }

}


[정답]

logHandler("Process() begin");

logHandler("Process() end");

fl.Logger

myClass.Process(myLogger);



4. 간단한 C# 속성(Property) 예문 입니다. 

   결과를 확인하고 괄호를 채우세요


[결과]

Student Info: Code = 001, Name = Zara, Age = 9

Student Info: Code = 001, Name = Zara, Age = 10


using System;

namespace tutorialspoint {


   class Student {

      private string code = "N.A";

      private string name = "not known";

      private int age = 0;

      

      // Declare a Code property of type string:

      public string Code {

          ( 채워주세요 )

      }

      

      // Declare a Name property of type string:

      public string Name {

          ( 채워주세요 )

      }

      

      // Declare a Age property of type int:

      public int Age {

          ( 채워주세요 )

      }

      public override string ToString() {

         return (   채워주세요   )

      }

   }

   

   class ExampleDemo {

      public static void Main() {

      

         // Create a new Student object:

         Student s = new Student();

         

         // Setting code, name and the age of the student

         s.Code = "001";

         s.Name = "Zara";

         s.Age = 9;

         Console.WriteLine("Student Info: {0}", s);

         

         //let us increase age

         s.Age += 1;

         Console.WriteLine("Student Info: {0}", s);

         Console.ReadKey();

      }

   }

}


[정답]

get { return code; }

set { code = value; }

get { return name; }

set { name = value; }

get { return age; }

set { age = value; }

$"Code = {Code}, Name = {Name}, Age = {Age}";



5. 자동구현 속성 입니다. 괄호를 채워주세요.


using System;

public class Customer

{

    public int ID {   (  )   }

    public string Name { (  ) }

}


public class AutoImplementedCustomerManager

{

    static void Main()

    {

        Customer cust = new Customer();

        cust.ID = 1;

        cust.Name = "Amelio Rosales";


        Console.WriteLine(

            "ID: {0}, Name: {1}",

            cust.ID,

            cust.Name);


        Console.ReadKey();

    }

}


[정답]

get; set;

get; set;


6. 간단한 C# 델리게이트(Delegate) 예문 입니다. 

   결과를 확인하고 괄호를 채우세요.


[실행결과]

Number: 10,000 

Number: 200 

Money: $ 10,000.00 

Money: $ 200.00


using System;

class Program

{

    // declare delegate

    public delegate (  채워주세요 );

 

    static void Main(string[] args)

    {

        // Print delegate points to PrintNumber

        Print printDel = (  );

 

        printDel(100000);

        printDel(200);

 

        // Print delegate points to PrintMoney

        printDel = (  );

 

        printDel(10000);

        printDel(200);

    }

 

    public static void PrintNumber(int num)

    {

        Console.WriteLine("Number: {0,-12:N0}", num);

    }

 

    public static void PrintMoney(int money)

    {

        Console.WriteLine("Money: {0:C}", money);

    }

}



[정답]

void Print(int value)

PrintNumber

PrintMoney



7. (이벤트, 델리게이트)실행결과를 확인하고 코드를 완성하세요. 


[실행결과] 

Dog 

Cat 

Mouse 

Mouse 


using System; 


public delegate void EventHandler(); 


class Program 

    public static ( 채워주세요  )  EventHandler _show; 


    static void Main() 

    { 

        // Add event handlers to Show event. 

        (  ) 


        // Invoke the event. 

        (  ) 

    } 


    static void Cat() 

    { 

        Console.WriteLine("Cat"); 

    } 


    static void Dog() 

    { 

        Console.WriteLine("Dog"); 

    } 


    static void Mouse() 

    { 

        Console.WriteLine("Mouse"); 

    } 

}


[정답]

event


_show += Dog;

_show += Cat;

_show += Mouse;

_show += Mouse;


_show(); 


8. (이벤트, 델리게이트)실행결과를 확인하고 코드를 완성하세요. 


[실행결과]

Sum = 11


using System;


public delegate (  채워주세요  );


class Program

{

    public event ( 채워 주세요) ;

    static void Main()

    {

        Program p = new Program();

        p.AddEvent += (  채워 주세요 );

        p.AddEvent(5);

        (  채워 주세요) ;


        Console.WriteLine($"Sum = {Adder.sum}" );

    }

}


public class Adder

{

    public static int sum;

    public static void Add(int i)    { sum += i;  }

}




[정답]

using System;


public delegate void AddDelegate(int a);


class Program

{

    // 이벤트 선언시 빈 델리게이트로 초기화 하면

    // 이벤트 가입자가 있는지 체크하지 않아도 된다.

    // if (AddEvent != null ) ...

    public event AddDelegate AddEvent = delegate { };

    static void Main()

    {

        Program p = new Program();

        p.AddEvent += new AddDelegate(Adder.Add);

        p.AddEvent(5);

        p.AddEvent(6);


        Console.WriteLine($"Sum = {Adder.sum}" );

    }

}


public class Adder

{

    public static int sum;

    public static void Add(int i)    { sum += i;  }

}


9. 윈폼으로 로또번호 6자리를 멀티쓰레드로 작성하세요.

   텍스트 박스 컨트롤 6개를 만들고 "로또번호생성" 버튼을 클릭하면

   Thread 6개를 만들고 Random 클래스를 이용하여 난수를 발생시켜

   Thread별로 각각 하나의 텍스트박스에 생성한 1에서 46까지의 정수 난수를

   출력하세요. 


1. Form1.cs


 


using System;


using System.Collections.Generic;


using System.ComponentModel;


using System.Data;


using System.Drawing;


using System.Linq;


using System.Text;


using System.Threading;


using System.Threading.Tasks;


using System.Windows.Forms;


 


namespace WindowsFormsApp4


{


    public partial class Form1 : Form


    {


        public Form1()


        {


            InitializeComponent();


        }


 


        private void button1_Click(object sender, EventArgs e)


        {


 


            Thread t1 = new Thread(() => GetNum(textBox1)); t1.Start();


            Thread t2 = new Thread(() => GetNum(textBox2)); t2.Start();


            Thread t3 = new Thread(() => GetNum(textBox3)); t3.Start();


            Thread t4 = new Thread(() => GetNum(textBox4)); t4.Start();


            Thread t5 = new Thread(() => GetNum(textBox5)); t5.Start();


            Thread t6 = new Thread(() => GetNum(textBox6)); t6.Start();


        }


 


        Random r = new Random();


        private void GetNum(TextBox t)


        {


            int n = r.Next(1, 46);


            SetText(t, n);


        }


        public void SetText(TextBox t, int n)


        {


            if (t.InvokeRequired)


            {


                Invoke((Action<TextBox, int>)SetText, t, n);


            }


            else


            {


                t.Text = n.ToString();


            }


        }


 


    }


}




2. Form1.Designer.cs


namespace WindowsFormsApp4

{

    partial class Form1

    {

        /// <summary>

        /// 필수 디자이너 변수입니다.

        /// </summary>

        private System.ComponentModel.IContainer components = null;


        /// <summary>

        /// 사용 중인 모든 리소스를 정리합니다.

        /// </summary>

        /// <param name="disposing">관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다.</param>

        protected override void Dispose(bool disposing)

        {

            if (disposing && (components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }


        #region Windows Form 디자이너에서 생성한 코드


        /// <summary>

        /// 디자이너 지원에 필요한 메서드입니다. 

        /// 이 메서드의 내용을 코드 편집기로 수정하지 마세요.

        /// </summary>

        private void InitializeComponent()

        {

            this.button1 = new System.Windows.Forms.Button();

            this.textBox1 = new System.Windows.Forms.TextBox();

            this.textBox2 = new System.Windows.Forms.TextBox();

            this.textBox3 = new System.Windows.Forms.TextBox();

            this.textBox4 = new System.Windows.Forms.TextBox();

            this.textBox5 = new System.Windows.Forms.TextBox();

            this.textBox6 = new System.Windows.Forms.TextBox();

            this.SuspendLayout();

            // 

            // button1

            // 

            this.button1.Location = new System.Drawing.Point(95, 137);

            this.button1.Name = "button1";

            this.button1.Size = new System.Drawing.Size(126, 63);

            this.button1.TabIndex = 0;

            this.button1.Text = "button1";

            this.button1.UseVisualStyleBackColor = true;

            this.button1.Click += new System.EventHandler(this.button1_Click);

            // 

            // textBox1

            // 

            this.textBox1.Font = new System.Drawing.Font("굴림", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

            this.textBox1.Location = new System.Drawing.Point(53, 66);

            this.textBox1.Name = "textBox1";

            this.textBox1.Size = new System.Drawing.Size(30, 29);

            this.textBox1.TabIndex = 1;

            // 

            // textBox2

            // 

            this.textBox2.Font = new System.Drawing.Font("굴림", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

            this.textBox2.Location = new System.Drawing.Point(89, 66);

            this.textBox2.Name = "textBox2";

            this.textBox2.Size = new System.Drawing.Size(30, 29);

            this.textBox2.TabIndex = 2;

            // 

            // textBox3

            // 

            this.textBox3.Font = new System.Drawing.Font("굴림", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

            this.textBox3.Location = new System.Drawing.Point(120, 66);

            this.textBox3.Name = "textBox3";

            this.textBox3.Size = new System.Drawing.Size(30, 29);

            this.textBox3.TabIndex = 3;

            // 

            // textBox4

            // 

            this.textBox4.Font = new System.Drawing.Font("굴림", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

            this.textBox4.Location = new System.Drawing.Point(155, 65);

            this.textBox4.Name = "textBox4";

            this.textBox4.Size = new System.Drawing.Size(30, 29);

            this.textBox4.TabIndex = 4;

            // 

            // textBox5

            // 

            this.textBox5.Font = new System.Drawing.Font("굴림", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

            this.textBox5.Location = new System.Drawing.Point(191, 65);

            this.textBox5.Name = "textBox5";

            this.textBox5.Size = new System.Drawing.Size(30, 29);

            this.textBox5.TabIndex = 5;

            // 

            // textBox6

            // 

            this.textBox6.Font = new System.Drawing.Font("굴림", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

            this.textBox6.Location = new System.Drawing.Point(227, 65);

            this.textBox6.Name = "textBox6";

            this.textBox6.Size = new System.Drawing.Size(30, 29);

            this.textBox6.TabIndex = 6;

            // 

            // Form1

            // 

            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

            this.ClientSize = new System.Drawing.Size(327, 244);

            this.Controls.Add(this.textBox6);

            this.Controls.Add(this.textBox5);

            this.Controls.Add(this.textBox4);

            this.Controls.Add(this.textBox3);

            this.Controls.Add(this.textBox2);

            this.Controls.Add(this.textBox1);

            this.Controls.Add(this.button1);

            this.Name = "Form1";

            this.Text = "Form1";

            this.ResumeLayout(false);

            this.PerformLayout();


        }


        #endregion


        private System.Windows.Forms.Button button1;

        private System.Windows.Forms.TextBox textBox1;

        private System.Windows.Forms.TextBox textBox2;

        private System.Windows.Forms.TextBox textBox3;

        private System.Windows.Forms.TextBox textBox4;

        private System.Windows.Forms.TextBox textBox5;

        private System.Windows.Forms.TextBox textBox6;

    }

}




10. (인덱서) 괄호를 채우세요.


using System;

namespace IndexerTest

{

    class Dept

    {

        public string[] emps = new string[3];

        (  인덱서 정의 하세요 )

    }

    class Program

    {

        static void Main(string[] args)

        {

            Dept d1 = new Dept();

            d1.emps[0] = "사원1"; d1.emps[1] = "사원2"; d1.emps[2] = "사원3";


            d1[0] = "사원1"; d1[1] = "사원2"; d1[2] = "사원3";

            Console.WriteLine(d1[0]);

        }

    }

}



[정답]

public string this[int i]

{

   get { return emps[i]; }

   set { emps[i] = value; }

}


(C#교육동영상)C# ADO.NET 실습 ODP.NET/ODAC 설치 오라클 함수 호출 실습, C#학원, WPF학원, 닷넷학원, 자바학원

  (C#교육동영상)C# ADO.NET 실습  ODP.NET/ODAC 설치  오라클 함수 호출 실습, C#학원, WPF학원, 닷넷학원, 자바학원 https://www.youtube.com/watch?v=qIPU85yAlzc&list=PLxU-i...