C#에서 사용자 정의 대표자는 어떻게 사용하고 생성됩니까?

StackOverflow https://stackoverflow.com/questions/618143

  •  03-07-2019
  •  | 
  •  

문제

.NET에서 Win Forms를 설계 할 때 대의원을 사용했습니다 ... 즉, 버튼을 드래그/드롭, 더블 클릭하고 MyButton_Click 이벤트를 채우십시오. C#에서 사용자 정의 대표를 작성하고 사용하는 방법을 이해하고 싶습니다.

C#에서 사용자 정의 대표자는 어떻게 사용하고 생성됩니까?

도움이 되었습니까?

해결책

주제에 대한 튜토리얼을 읽는 것이 좋습니다.

기본적으로 대의원 유형을 선언합니다.

public delegate void MyDelegate(string message);

그런 다음 직접 할당하고 전화 할 수 있습니다.

MyDelegate = SomeFunction;
MyDelegate("Hello, bunny");

또는 이벤트를 만듭니다.

public event MyDelegate MyEvent;

그런 다음 외부에서 이벤트 핸들러를 다음과 같이 추가 할 수 있습니다.

SomeObject.MyEvent += SomeFunction;

Visual Studio는 이것에 도움이됩니다. +=를 입력 한 후에는 Tab-TAB를 누르면 처리기가 생성됩니다.

그런 다음 개체 내부에서 이벤트를 발사 할 수 있습니다.

if (MyEvent != null) {
    MyEvent("Hello, bunny");
}

그것이 기본 사용법입니다.

다른 팁

public delegate void testDelegate(string s, int i);

private void callDelegate()
{
    testDelegate td = new testDelegate(Test);

    td.Invoke("my text", 1);
}

private void Test(string s, int i)
{
    Console.WriteLine(s);
    Console.WriteLine(i.ToString());
}

중복은 아니지만 (중복을 찾을 수 없음) 많은 정보가 있습니다.

이벤트와 대표들 사이의 차이 시작하려면보십시오

사용시기. . .

폐쇄는 무엇입니까?

Whis는이 대의원입니다. . .

이 도움을 바랍니다

광범위한 답변은 이것을 확인하십시오 기사 ~에 의해 모하마드 할라 비. 짧은 답변은 C :/Program Files/Microsoft Visual Studio 9.0/샘플/1033/폴더 에서이 약간 수정 된 예를 확인하십시오 ...

using System;
using System.IO; 


namespace DelegateExample
{
  class Program
  {
    public delegate void PrintDelegate ( string s );

    public static void Main ()
    {
      PrintDelegate delFileWriter = new PrintDelegate ( PrintFoFile );
      PrintDelegate delConsoleWriter = new PrintDelegate ( PrintToConsole);
      Console.WriteLine ( "PRINT FIRST TO FILE by passing the print delegate -- DisplayMethod ( delFileWriter )" );

      DisplayMethod ( delFileWriter );      //prints to file
      Console.WriteLine ( "PRINT SECOND TO CONSOLE by passing the print delegate -- DisplayMethod ( delConsoleWriter )" );
      DisplayMethod ( delConsoleWriter ); //prints to the console
      Console.WriteLine ( "Press enter to exit" );
      Console.ReadLine ();

    }

    static void PrintFoFile ( string s )
    {
      StreamWriter objStreamWriter = File.CreateText( AppDomain.CurrentDomain.BaseDirectory.ToString() + "file.txt" );
      objStreamWriter.WriteLine ( s );
      objStreamWriter.Flush ();
      objStreamWriter.Close ();
    }


    public static void DisplayMethod ( PrintDelegate delPrintingMethod )
    { 
      delPrintingMethod( "The stuff to print regardless of where it will go to" ) ;
    }

    static void PrintToConsole ( string s )
    {
      Console.WriteLine ( s );    
    } //eof method 
  } //eof classs 
} //eof namespace 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top