Type.GetInterface() मेथड का उपयोग करके नाम से विशिष्ट इंटरफेस प्राप्त करें।
सिंटैक्स
public Type GetInterface(string name);
public Type GetInterface(string name, bool ignoreCase);
उदाहरण 1: डिफ़ॉल्ट (केस-सेंसिटिव)
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
उदाहरण 2: केस-इनसेंसिटिव खोज
using System;
public class Demo {
public static void Main() {
Type type = typeof(float);
Type myInterface = type.GetInterface("IFormattable", true); // ignoreCase = true
Console.WriteLine("Interface = " + myInterface);
}
}
आउटपुट
Interface = System.IFormattable
महत्वपूर्ण बिंदु
nameनल नहीं हो सकता (ArgumentNullException)- नहीं मिलने पर
nullलौटाता है (एक्सेप्शन नहीं) ignoreCaseपैरामीटर केस-इनसेंसिटिव मिलान के लिए- इनहेरिटेड इंटरफेसेज भी शामिल हैं
व्यावहारिक उदाहरण: नल चेकिंग
Type type = typeof(MyClass);
Type iformattable = type.GetInterface("IFormattable");
if (iformattable != null) {
Console.WriteLine("Implements IFormattable");
} else {
Console.WriteLine("Does not implement IFormattable");
}
Type icloneable = type.GetInterface("ICloneable");
Console.WriteLine(icloneable ?? "Not found"); // Not found
कस्टम क्लास उदाहरण
public interface IRepository { }
public interface ICacheable { }
public interface ILoggable { }
public class UserRepository : IRepository, ICacheable, ILoggable { }
// उपयोग
Type repoType = typeof(UserRepository);
var cacheable = repoType.GetInterface("ICacheable");
var loggable = repoType.GetInterface("ILoggable");
var repo = repoType.GetInterface("IRepository`1"); // जेनेरिक इंटरफेस नाम
Console.WriteLine(cacheable); // ICacheable
Console.WriteLine(loggable); // ILoggable
Console.WriteLine(repo); // IRepository`1[User]
जेनेरिक इंटरफेस नाम फॉर्मेट
- खुला जेनेरिक:
"IRepository`1"(बैकटिक + टाइप पैरामीटर काउंट) - बंद जेनेरिक:
"IRepository`1[User]" type.GetInterfaces()से नाम कॉपी करें
GetInterface vs GetInterfaces
| मेथड | रिटर्न | केस सेंसिटिव | उपयोग |
|---|---|---|---|
GetInterface(name) | Type या null | हाँ | विशिष्ट इंटरफेस |
GetInterface(name, true) | Type या null | नहीं | केस-इनसेंसिटिव |
GetInterfaces() | Type[] | N/A | सभी इंटरफेसेज |