C# 如何检查一个类是否实现了泛型接口(interface)?

标签 c# generics interface types

如何获取实例的通用接口(interface)类型?

假设这段代码:

interface IMyInterface<T>
{
    T MyProperty { get; set; }
}
class MyClass : IMyInterface<int> 
{
    #region IMyInterface<T> Members
    public int MyProperty
    {
        get;
        set;
    }
    #endregion
}


MyClass myClass = new MyClass();

/* returns the interface */
Type[] myinterfaces = myClass.GetType().GetInterfaces();

/* returns null */
Type myinterface = myClass.GetType().GetInterface(typeof(IMyInterface<int>).FullName);

最佳答案

为了获得通用接口(interface),您需要使用Name 属性而不是FullName 属性:

MyClass myClass = new MyClass();
Type myinterface = myClass.GetType()
                          .GetInterface(typeof(IMyInterface<int>).Name);

Assert.That(myinterface, Is.Not.Null);

关于C# 如何检查一个类是否实现了泛型接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2522461/

相关文章:

java - 类型参数 T 不在其范围内;应该扩展 MyBaseClass

java - 带有接口(interface)的 "Cannot reduce the visibility of the inherited method"的含义

c# - Basic Razor 网站和 NuGet ServiceStack 无法构建

swift - 为什么 Swift 被设计成不允许协议(protocol)泛型?

基于 C# 泛型的对象到对象映射器问题

swift - 你如何编写一个协议(protocol)来指定 Swift 中算术运算符的存在?

c++ - 为 QFS 构建 C++ 包装器

c# - 如何使用 c# 驱动程序删除 mongodb 文档中的嵌套数组元素

c# - 解析不同的HttpClient

c# - 为什么重写 == 必须重写 equals?