2022년 2월 1일 화요일

(동영상)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...