【发布时间】:2021-03-27 01:22:23
【问题描述】:
我有一个开放的泛型类型定义,想检查这个开放的定义是否实现了开放的接口定义。
interface IMyInterface<T>
{}
class GoodType<T> : IMyInterface<T> where T : Enum
{
}
class BadType<T> where T : Enum
{
}
static bool IsOpenGenericTypeImplementing(Type candidate, Type iface) =>
candidate.IsGenericTypeDefinition &&
candidate.GetGenericArguments().Length == 1 &&
candidate.MakeGenericType(typeof(object)).IsAssignableTo(iface.MakeGenericType(typeof(object))); // does not work
[Fact]
void Test()
{
Assert.True(IsOpenGenericTypeImplementing(typeof(GoodType<>), typeof(IMyInterface<>)));
Assert.False(IsOpenGenericTypeImplementing(typeof(BadType<>), typeof(IMyInterface<>)));
}
上述方法的问题在于,由于Enum 类型约束(ArgumentException),它会失败。
我发现了一些类似的问题,但似乎都需要一个封闭的泛型类型定义(<T> 而不是<>)。
例如。 Finding out if a type implements a generic interface
【问题讨论】:
-
this 会回答您的问题吗? (请注意,接受的答案比它需要的要昂贵得多,因为它多次迭代接口列表,每种基本类型一次)
-
following test will fail (exception)什么异常? -
您是否打算让您的
SomeType<T>实现IEnumerable<T>顺便说一句?目前有一个泛型类型约束where T : IEnumerable<T> -
@canton7 你说得对,我会解决这个问题。
-
我更新了问题以使事情更清楚,抱歉(初始)问题代码质量不佳。 @canton7:是的,stackoverflow.com/questions/5461295/… 中的答案解决了我的问题。我会尝试理解为什么:-) 然后尝试将其标记为重复。谢谢!
标签: c# generics reflection types interface