【发布时间】:2017-12-01 13:38:44
【问题描述】:
我正在尝试从实现类型的依赖注入器中获取所有通用服务
protected List<ServiceDescriptor> GetGenericServicesFromGenericTypeDefinition(IServiceCollection services, Type baseGenericTypeDefinition)
{
if(false == baseGenericTypeDefinition.IsGenericTypeDefinition)
{
throw new Exception($"Invalid Argument {nameof(baseGenericTypeDefinition)}");
}
//TODO: check the base type recursively
var genericImplementations = services.Where(s => s?.ImplementationType.GetTypeInfo().IsGenericType ?? false)
.ToList();
//.... Omitted unrelated to issue
}
奇怪的是,当它尝试创建 genericImplementations List 时,我收到一个错误
System.ArgumentNullException: '值不能为空。'
我检查了服务它不是空的,但是实现类型是。这怎么可能,这与函数的构造方式有什么关系吗?
编辑 我如何错误地使用 Elvis Operator?如您所见,s 有一个值。从图片中。错误是从检查的类型产生的,这怎么可能?
【问题讨论】:
-
显示堆栈跟踪。我们不知道异常是从哪里来的。
-
@TimSchmelter 我认为它描述得很好。在获取 genericImplementations 时,他在 serviceCollection 中有一个不为空的服务,但具有空的 ImplementationType。我能猜到它会往哪里扔
-
即使您正在检查 service 是否为 null,但不能保证其属性不为 null,因此您需要为每个属性添加 elvis 运算符
-
@LordWilmore:即使你很清楚,每个人都应该始终发布完整的堆栈跟踪。特别是如果您使用 LINQ 查询。当然,您可以在任何地方放置
?。但是在这样做之前,您应该了解导致异常的原因。也许方法是错误的,您只需使用null-conditonal-operator 隐藏错误。 -
您是在服务中获得列表还是只是为空?
标签: c# asp.net-core signalr signalr-hub asp.net-core-2.0