【问题标题】:How can I check whether `SomeType<>` implements `SomeInterface<>`? [duplicate]如何检查 `SomeType<>` 是否实现了 `SomeInterface<>`? [复制]
【发布时间】: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),它会失败。

我发现了一些类似的问题,但似乎都需要一个封闭的泛型类型定义(&lt;T&gt; 而不是&lt;&gt;)。 例如。 Finding out if a type implements a generic interface

【问题讨论】:

  • this 会回答您的问题吗? (请注意,接受的答案比它需要的要昂贵得多,因为它多次迭代接口列表,每种基本类型一次)
  • following test will fail (exception)什么异常?
  • 您是否打算让您的SomeType&lt;T&gt; 实现IEnumerable&lt;T&gt; 顺便说一句?目前有一个泛型类型约束where T : IEnumerable&lt;T&gt;
  • @canton7 你说得对,我会解决这个问题。
  • 我更新了问题以使事情更清楚,抱歉(初始)问题代码质量不佳。 @canton7:是的,stackoverflow.com/questions/5461295/… 中的答案解决了我的问题。我会尝试理解为什么:-) 然后尝试将其标记为重复。谢谢!

标签: c# generics reflection types interface


【解决方案1】:

在静态方法中添加以下内容:

candidate.GetInterfaces().Contains(typeof(IEnumerable))

【讨论】:

  • 这虽然在技术上对于这个特定场景是正确的(并且只是因为IEnumerable&lt;T&gt; 实现了IEnumerable)并没有涵盖一般情况,这是 OP 所要求的
  • @canton7:完全正确。我将更新我的问题并使用替代界面以使这一点更清楚。
猜你喜欢
  • 2012-04-27
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-29
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
相关资源
最近更新 更多