How can I make code below return true
?
handler
variable defined as anobject
on purpose to mimic the actual environment.I already read 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
{
}
It is the other way round!
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();
}
From the documentation for IsInstanceOfType
:
Determines whether the specified object is an instance of the current Type.
So, you are asking whether IIntegrationEventHandler<TestIntegrationEvent>
is an instance of type TestIntegrationEventHandler
, which is false of course. Although I really think that the method's name does not help much...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.