首页 > 解决方案 > 不可转换的委托返回类型在哪里?

问题描述

尝试使用委托从我的 DI 容器返回服务,基于枚举属性上设置的类型,但遇到 CS1662 错误,其中某些返回类型不可隐式转换。我看不出问题出在哪里。

委托看起来像这样,其中的键应该是 a ParserType,而它又用 装饰ParserTypeInfoAttribute,它提供属性ServiceType,它设置 IValueParser 类型以从容器中检索。

我这样做是因为 ParserType 枚举将来可能会增长,所以我不想在代码中使用多个开关来查找与枚举值相关的属性,而是在 ParserTypeInfo 属性上定义并修改/只设置在那里。我认为通用属性会拯救我,但这还不是一个选项(C# 10)。

我怎样才能使这项工作?

builder.Services.AddTransient<Func<ParserType, IValueParser>>(serviceProvider => key =>
{
  IValueParser serviceType = (key as ParserType).GetAttribute<ParserTypeInfoAttribute>()?.ServiceType;

  if (serviceType == null) 
    throw new Exception();

  return serviceProvider.GetService(serviceType);
});
// attribute
[ParserTypeInfo(typeof(StringValueParser))]
// implementation
public class ParserTypeInfoAttribute : Attribute
{
  internal ParserTypeInfoAttribute(Type serviceType)
  {
    ServiceType = serviceType as IValueParser;
  }

  public Type ServiceType { get; private set; }
}

编辑 - 工作正常,如果我不混合类型:

builder.Services.AddTransient<Func<ParserType, IValueParser>>(serviceProvider => key =>
{
  Type serviceType = (key as ParserType).GetAttribute<ParserTypeInfoAttribute>()?.ServiceType;

  if (serviceType == null) 
    throw new Exception();

  // given I know the ParserType key will have a corresponding parser available on the container, this cast is safe.
  return serviceProvider.GetService(serviceType) as IValueParser;
});

标签: c#asp.net-coredelegates

解决方案


推荐阅读