如何使下面的代码返回true
?
handler
变量被定义为object
,目的是模仿实际环境。我已经读过https://stackoverflow.com/questions/12160460/when-is-obj-gettype-isinstanceoftypetypeofmyclass-true
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
{
}
答案 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();
}
从documentation到IsInstanceOfType
:
确定指定的对象是否是当前Type的实例。
因此,您要询问IIntegrationEventHandler<TestIntegrationEvent>
是否为类型TestIntegrationEventHandler
的实例,这当然是错误的。尽管我真的认为该方法的名称没有太大帮助...