【问题标题】:Query the generic type definition of a class implementing a generic interface查询实现泛型接口的类的泛型类型定义
【发布时间】:2015-01-18 23:14:00
【问题描述】:

我有一个 C# 通用接口 interface IMonitor<in T> where T:IEvent

所以 Monitor 应该是通用的 Event 类型

然后我有一个包含监视器集合的类

List<IMonitor<IEvent>> monitors

我正在向它添加IMonitor<IEvent> 的实现。例如。 monitors.Add(new AConcreteMonitor<AConcreteEvent>())

现在,在Trigger(IEvent event) 方法中,我想遍历监视器集合并通知与event 具有相同通用类型的所有监视器。

我有:

void Trigger(IEvent event)
    foreach (var monitor in monitors)
        {
            if (
                monitor.GetType()
                    .GetInterfaces()
                    .Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == event.GetType()))
            {
                monitor.Notify(event);
            }
        }
}

(避免使用 LINQ 以简化调试...)

即使集合中有AConcreteMonitor<AConcreteEvent> 监视器并且触发eventAConcreteEvent,条件永远不会评估为真。调试时,GetGenericTypeDefinition() 的计算结果为 IMonitor'1

Q U E S T I O N :

如果在该 foreach 循环中 eventAConcreteMonitor<AConcreteEvent>(),我如何获得 interface IMonitor<in T> where T:IEvent 的实际 T,即 AConcreteEvent

【问题讨论】:

    标签: c# generics types interface covariance


    【解决方案1】:

    现在我输入了问题并一路“雅虎”了一些东西,我发现我可以使用通用方法,然后只需查询typeof(T)

    void Trigger<T>(IEvent event) where T:IMonitor<IEvent>
    
    foreach (var monitor in monitors.Where(m=> m.GetType() == typeof(T)))
    {
        monitor.Notify(event);
    }
    

    简单!

    以防万一有人遇到类似问题...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      相关资源
      最近更新 更多