Como são delegados definidos pelo usuário usado e criado em C #?
Pergunta
Eu usei delegados ao projetar formas vitória em .NET ... ou seja arrastar / soltar um botão, clique duas vezes e preencha o evento myButton_click. Eu quero entender como criar e usar delegados definidos pelo usuário em C #.
Como são delegados definidos pelo usuário usados ??e criados em C #?
Solução
Eu sugiro a leitura de um tutorial sobre o assunto.
Basicamente, você declarar um tipo de delegado:
public delegate void MyDelegate(string message);
Em seguida, você pode atribuir e chamá-lo diretamente:
MyDelegate = SomeFunction;
MyDelegate("Hello, bunny");
Ou você criar um evento:
public event MyDelegate MyEvent;
Em seguida, você pode adicionar um manipulador de eventos do lado de fora como este:
SomeObject.MyEvent += SomeFunction;
Visual Studio é útil com isso. Depois que você entrou no + =, apenas pressione tab-guia e ele irá criar o manipulador para você.
Depois, você pode acionar o evento de dentro do objeto:
if (MyEvent != null) {
MyEvent("Hello, bunny");
}
Isso é o uso básico.
Outras dicas
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());
}
Não é uma duplicata (não consegue encontrar uma duplicata), mas muita informação aqui no SO, tente
differnce entre Eventos e representantes para obter começou, em seguida olhar para
Whis é este delegado fazendo . . .
Hope estes ajudam
Como resposta ampla verificar este artigo por Mohamad Halabi . Como resposta mais curta verificar este exemplo ligeiramente modificado a partir da c: / Program Files / Microsoft Visual Studio 9.0 / Amostras / 1033 / pasta ...
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