在C#中,typeof
关键字主要用于获取一个类型的类型信息。它不能直接用于接口实现,但是你可以使用typeof
来获取接口类型的类型信息,然后使用这个信息来处理实现了该接口的对象。
例如,假设你有一个接口IMyInterface
和一个实现了该接口的类MyClass
:
public interface IMyInterface { void MyMethod(); } public class MyClass : IMyInterface { public void MyMethod() { Console.WriteLine("MyMethod called."); } }
要检查一个对象是否实现了IMyInterface
接口,你可以使用is
关键字:
object obj = new MyClass(); if (obj is IMyInterface) { IMyInterface myInterface = (IMyInterface)obj; myInterface.MyMethod(); } else { Console.WriteLine("Object does not implement IMyInterface."); }
如果你想要使用typeof
来获取接口类型的类型信息,可以这样做:
Type interfaceType = typeof(IMyInterface); Console.WriteLine($"The type of IMyInterface is: {interfaceType}");