C# में Type.GetInterfaces() मेथड वर्तमान Type द्वारा लागू या इनहेरिट किए गए सभी इंटरफेस को एक सरणी के रूप में लौटाता है।
सिंटैक्स
public abstract Type[] GetInterfaces ();
उदाहरण 1: float प्रकार के इंटरफेस
using System;
public class Demo
{
public static void Main()
{
Type type = typeof(float);
Type myInterface = type.GetInterface("IFormattable", true);
Type[] myInterfaces = type.GetInterfaces();
Console.WriteLine("Interface = " + myInterface);
Console.WriteLine("All the Interfaces...");
for (int i = 0; i < myInterfaces.Length; i++)
Console.WriteLine("" + myInterfaces[i]);
}
}
आउटपुट
Interface = System.IFormattable All the Interfaces... System.IComparable System.IFormattable System.IConvertible System.IComparable`1[System.Single] System.IEquatable`1[System.Single]
उदाहरण 2: int प्रकार के इंटरफेस
using System;
public class Demo
{
public static void Main()
{
Type type = typeof(int);
Type myInterface = type.GetInterface("IFormattable");
Type[] myInterfaces = type.GetInterfaces();
Console.WriteLine("Interface = " + myInterface);
Console.WriteLine("All the Interfaces...");
for (int i = 0; i < myInterfaces.Length; i++)
Console.WriteLine("" + myInterfaces[i]);
}
}
आउटपुट
Interface = System.IFormattable All the Interfaces... System.IComparable System.IFormattable System.IConvertible System.IComparable`1[System.Int32] System.IEquatable`1[System.Int32]
उदाहरण 3: कस्टम क्लास के इंटरफेस
using System;
using System.Collections.Generic;
public interface IAnimal { void Speak(); }
public interface IPet { string Name { get; set; } }
public class Dog : IAnimal, IPet, IComparable
{
public string Name { get; set; }
public void Speak() => Console.WriteLine("Woof!");
public int CompareTo(Dog other) => Name.CompareTo(other.Name);
}
public class Demo
{
public static void Main()
{
Type type = typeof(Dog);
Type[] interfaces = type.GetInterfaces();
Console.WriteLine($"Dog इंटरफेस लागू करता है ({interfaces.Length}):");
foreach (var iface in interfaces)
Console.WriteLine($" - {iface.Name}");
}
}
आउटपुट
Dog इंटरफेस लागू करता है (5): - IAnimal - IPet - IComparable`1 - IComparable - IEquatable`1
मुख्य बिंदु
- सभी इंटरफेस लौटाता है: सीधे लागू, बेस क्लास से इनहेरिटेड, और जेनेरिक इंटरफेस
- क्रम अनिर्दिष्ट है - इस पर निर्भर न करें
- यदि कोई इंटरफेस नहीं है, तो खाली सरणी लौटाता है (null नहीं)
- GetInterface(name) का उपयोग करके विशिष्ट इंटरफेस खोजें
- रिफ्लेक्शन-आधारित सिस्टम, प्लगइन आर्किटेक्चर, सीरियलाइज़र के लिए उपयोगी
सामान्य इंटरफेस (प्रिमिटिव प्रकारों के लिए)
- IComparable / IComparable<T> - क्रम तुलना
- IEquatable<T> - टाइप-सेफ समानता
- IFormattable - कस्टम स्ट्रिंग फॉर्मेटिंग
- IConvertible - बेस प्रकार में रूपांतरण