如何正确评估.GetType()。IsInstanceOfType(typeof(Interface <>))

时间:2018-11-28 05:12:27

标签: c#

如何使下面的代码返回true

  
      
  1. handler变量被定义为object,目的是模仿实际环境。

  2.   
  3. 我已经读过https://stackoverflow.com/questions/12160460/when-is-obj-gettype-isinstanceoftypetypeofmyclass-true

  4.   
void Main()
{
    object handler = new TestIntegrationEventHandler();
    Type eventType = typeof(TestIntegrationEvent);
    Type concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
    Console.WriteLine(handler.GetType().IsInstanceOfType(concreteType));
}

public class TestIntegrationEvent : IntegrationEvent
{
}

public class IntegrationEvent
{
}

public class TestIntegrationEventHandler : IIntegrationEventHandler<TestIntegrationEvent>
{
    public async Task Handle(TestIntegrationEvent @event)
    {
    }
}

public interface IIntegrationEventHandler<in TIntegrationEvent> : IIntegrationEventHandler where TIntegrationEvent : IntegrationEvent
{
    Task Handle(TIntegrationEvent @event);
}

public interface IIntegrationEventHandler
{
}

1 个答案:

答案 0 :(得分:2)

反过来!

private static void Main()
{
    object handler = new TestIntegrationEventHandler();
    Type eventType = typeof(TestIntegrationEvent);
    Type concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
    Console.WriteLine(concreteType.IsInstanceOfType(handler));
    Console.ReadLine();
}

documentationIsInstanceOfType

  

确定指定的对象是否是当前Type的实例。

因此,您要询问IIntegrationEventHandler<TestIntegrationEvent>是否为类型TestIntegrationEventHandler的实例,这当然是错误的。尽管我真的认为该方法的名称没有太大帮助...