1

给定一个类,我如何找到 INotificationHandler<> 的类型:

public class OtherClass : INotificationHandler<Aggregate>, INotificationHandler<Quote>
{
  /* */
}

var typesList = [] { typeof(OtherClass) };

var result = MagicFunctionToGetTemplateTypesForNotificationHandlerInterface(typesList)

// where result = [] { typeof(Aggregate), typeof(Quote) };

我正在考虑沿着这条路走,GetType().GenericTypeArguments[0]但是想先检查是否有更安全的方法。

我已经尝试搜索并欣赏这很可能是重复的,如果是这样,请告诉我,我将删除。

4

1 回答 1

1

你可以尝试这样的事情:

var result = typeof(OtherClass).GetInterfaces()
    .Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(INotificationHandler<>))
    .Select(x => x.GetGenericArguments()[0])
    .ToArray();
于 2020-04-19T16:04:29.540 回答