C#-এ Type.GetInterface() মেথডটি বর্তমান Type-এর দ্বারা ইমপ্লিমেন্ট বা ইনহেরিট করা একটি নির্দিষ্ট ইন্টারফেস খুঁজে বের করতে ব্যবহৃত হয়। এটি ইন্টারফেসের নাম দিয়ে সার্চ করে।
সিনট্যাক্স (Syntax)
public Type GetInterface(string name);
public abstract Type GetInterface(string name, bool ignoreCase);
প্যারামিটার:
name- খুঁজতে চাওয়া ইন্টারফেসের নামignoreCase-trueহলে কেস-ইনসেনসিটিভ সার্চ করা হবে
উদাহরণ ১: ডিফল্ট কেস-সেনসিটিভ সার্চ
using System;
public class Demo
{
public static void Main()
{
Type type = typeof(double);
Type myInterface = type.GetInterface("IFormattable");
Console.WriteLine("Interface = " + myInterface);
}
}
আউটপুট
Interface = System.IFormattable
উদাহরণ ২: কেস-ইনসেনসিটিভ সার্চ
using System;
public class Demo
{
public static void Main()
{
Type type = typeof(float);
// "iformattable" ছোট হাতের অক্ষরে, ignoreCase = true
Type myInterface = type.GetInterface("iformattable", true);
Console.WriteLine("Interface = " + myInterface);
}
}
আউটপুট
Interface = System.IFormattable
খুঁজে না পাওয়া হলে কী হয়?
যদি ইন্টারফেসটি না পাওয়া যায়, তবে মেথডটি null ফেরত দেয়। কোনো এক্সেপশন ফেলে না।
উদাহরণ: নন-ইগজিস্টিং ইন্টারফেস
using System;
public class Demo
{
public static void Main()
{
Type type = typeof(int);
Type iface = type.GetInterface("INonExistentInterface");
if (iface == null)
Console.WriteLine("Interface not found!");
else
Console.WriteLine("Found: " + iface);
}
}
আউটপুট
Interface not found!
GetInterface() vs GetInterfaces()
| মেথড | রিটার্ন | ব্যবহার |
|---|---|---|
GetInterface(name) | Type বা null | নির্দিষ্ট ইন্টারফেস খুঁজতে |
GetInterfaces() | Type[] | সব ইন্টারফেস তালিকা পেতে |
প্রয়োগিক উদাহরণ: রানটাইমে ইন্টারফেস চেক
using System;
public interface ISerializable { void Serialize(); }
public interface ILoggable { void Log(); }
public class User : ISerializable { public void Serialize() { } }
public class Admin : ISerializable, ILoggable { public void Serialize() { } public void Log() { } }
public class Demo
{
public static void Process(object obj)
{
Type type = obj.GetType();
// শুধু ILoggable ইমপ্লিমেন্ট করা অবজেক্টের জন্য লগিং
if (type.GetInterface("ILoggable") != null)
{
Console.WriteLine($"Logging {type.Name}...");
((ILoggable)obj).Log();
}
// সব অবজেক্ট সিরিয়ালাইজ
((ISerializable)obj).Serialize();
}
public static void Main()
{
Process(new User());
Process(new Admin());
}
}
টিপস: কেস-ইনসেনসিটিভ সার্চের জন্য দ্বিতীয় ওভারলোডে ignoreCase: true পাস করুন।