Вы находитесь на странице: 1из 2

DELEGATE IN JAVA

package mypack;

import java.lang.reflect.*;
import java.io.*;
public class Test
{
public static void main(String[] args) throws Exception
{
String[] list= {"to","be","or","not","to","be"};
Method m1 = Test.class.getMethod("toConsole",
new Class[] {String.class});
display(m1, list);
Method m2 = Test.class.getMethod("toFile",
new Class[] {String.class});
display (m2, list);
}
public static void toConsole (String str)
{
System.out.print(str+" ");
}
public static void toFile (String s)
{
File f = new File("delegate.txt");
try{
PrintWriter fileOut =
new PrintWriter(new FileOutputStream(f));
fileOut.write(s);
fileOut.flush();
fileOut.close();
}catch(IOException ioe) {}
}
public static void display(Method m, String[] list)
{
for(int k = 0; k < list.length; k++) {
try {
Object[] args = {new String(list[k])};
m.invoke(null, args);
}catch(Exception e) {}
}
}
}
DELEGATE IN C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateCSEx
{
public class DelegateTest
{
public delegate void Print(String s);
public static void Main()
{
Print s = new Print(toConsole);
Print v = new Print(toFile);
Display(s);
Display(v);
}
public static void toConsole(String str)
{
Console.WriteLine(str);
}
public static void toFile(String s)
{

StreamWriter fileOut = new StreamWriter("delegate.txt");
fileOut.WriteLine(s);
fileOut.Flush();
fileOut.Close();
}
public static void Display(Print pMethod)
{
pMethod("This should be displayed in the console");
}
}
}

Вам также может понравиться