C# でクラスがどのインタフェースを実装しているかが知りたくなることが、稀に良くあります。
■ Type.GetInterfaces メソッド
Type.GetInterfaces メソッドで簡単に取得できます。
■ 実例
namespace ConsoleApp1 に次のインタフェースとクラスがあるものとします。
interface IMyInterface1 { } interface IMyInterface2 { } class MyClass1 : IMyInterface1, IMyInterface2 { }
このクラスに対して次のコードでインタフェースが取得できます。
var type = typeof(MyClass1); var interfaes = type.GetInterfaces(); foreach (var @interface in interfaes) Console.WriteLine(@interface.FullName);
実行結果
ConsoleApp1.IMyInterface1 ConsoleApp1.IMyInterface2
かんたんですね。
■ クラスのインスタンスからインタフェースを取得する
クラスの型からでなくインスタンスからインタフェースを取得する場合です。
クラスのインスタンスは GetInterfaces() メソッドを持たないのでひと手間書けて、インスタンスから Type を取得する必要があります。Type を取得したらあとは前述と同じ手順です。
var class1 = new MyClass1(); var type = class1.GetType(); var interfaes = type.GetInterfaces(); foreach (var @interface in interfaes) Console.WriteLine(@interface.FullName);
実行結果
ConsoleApp1.IMyInterface1 ConsoleApp1.IMyInterface2
同じ結果が得られました。
かんたんですね。