কম্পিউটার

C# এ প্রতিনিধি কি?


C# এ একটি প্রতিনিধি হল পদ্ধতির একটি রেফারেন্স। একটি প্রতিনিধি হল একটি রেফারেন্স টাইপ ভেরিয়েবল যা একটি পদ্ধতির রেফারেন্স ধারণ করে। রেফারেন্স রানটাইমে পরিবর্তন করা যেতে পারে।

প্রতিনিধিরা বিশেষ করে ইভেন্ট বাস্তবায়ন এবং কল-ব্যাক পদ্ধতির জন্য ব্যবহৃত হয়। সমস্ত প্রতিনিধিরা নিহিতভাবে System.Delegate ক্লাস থেকে প্রাপ্ত।

আসুন দেখি কিভাবে C# এ প্রতিনিধি ঘোষণা করা যায়।

delegate <return type> <delegate-name> <parameter list>

C# এ প্রতিনিধিদের সাথে কিভাবে কাজ করতে হয় তা শিখতে একটি উদাহরণ দেখা যাক।

উদাহরণ

using System;
using System.IO;

namespace DelegateAppl {

   class PrintString {
      static FileStream fs;
      static StreamWriter sw;

      // delegate declaration
      public delegate void printString(string s);

      // this method prints to the console
      public static void WriteToScreen(string str) {
         Console.WriteLine("The String is: {0}", str);
      }

      //this method prints to a file
      public static void WriteToFile(string s) {
         fs = new FileStream("c:\\message.txt",
         FileMode.Append, FileAccess.Write);
         sw = new StreamWriter(fs);
         sw.WriteLine(s);
         sw.Flush();
         sw.Close();
         fs.Close();
      }

      // this method takes the delegate as a parameter and uses it to
      // call the methods as required
      public static void sendString(printString ps) {
         ps("Hello World");
      }

      static void Main(string[] args) {
         printString ps1 = new printString(WriteToScreen);
         printString ps2 = new printString(WriteToFile);
         sendString(ps1);
         sendString(ps2);
         Console.ReadKey();
      }
   }  
}

আউটপুট

The String is: Hello World


  1. C# এ জেনেরিক প্রতিনিধি কি?

  2. C# এ ইনডেক্সার কি?

  3. C# এ নামস্থান কি?

  4. C# এ প্রতিনিধি কি?