Jeder, der danach sucht, könnte die folgende Erweiterungsmethode nützlich finden:
public static class TypeExtensions
{
public static bool ImplementsInterface(this Type type, Type @interface)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (@interface == null)
{
throw new ArgumentNullException(nameof(@interface));
}
var interfaces = type.GetInterfaces();
if (@interface.IsGenericTypeDefinition)
{
foreach (var item in interfaces)
{
if (item.IsConstructedGenericType && item.GetGenericTypeDefinition() == @interface)
{
return true;
}
}
}
else
{
foreach (var item in interfaces)
{
if (item == @interface)
{
return true;
}
}
}
return false;
}
}
xUnit-Tests:
public class TypeExtensionTests
{
[Theory]
[InlineData(typeof(string), typeof(IList), false)]
[InlineData(typeof(List<>), typeof(IList<int>), false)]
[InlineData(typeof(List<>), typeof(IList<>), true)]
[InlineData(typeof(List<int>), typeof(IList<>), true)]
[InlineData(typeof(List<int>), typeof(IList<int>), true)]
[InlineData(typeof(List<int>), typeof(IList<string>), false)]
public void ValidateTypeImplementsInterface(Type type, Type @interface, bool expect)
{
var output = type.ImplementsInterface(@interface);
Assert.Equal(expect, output);
}
}