c# – 如何确定一个类是否实现了特定的接口

假设我有类似的课程

interface ISampleInterface
{
  void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation: 
void ISampleInterface.SampleMethod()
{
    // Method implementation.
}

static void Main()
{
    // Declare an interface instance.
    ISampleInterface obj = new ImplementationClass();

    // Call the member.
    obj.SampleMethod();
}
}

从main方法我怎样才能确定ImplementationClass类在编写如下代码之前实现ISampleInterface

SampleInterface obj = new ImplementationClass();
obj.SampleMethod();

有什么办法….请讨论.谢谢.

解决方法

你可以使用反射:

bool result = typeof(ISampleInterface).IsAssignableFrom(typeof(ImplementationClass));

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...