c# - 不可转换的委托返回类型在哪里?
问题描述
尝试使用委托从我的 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;
});
解决方案
推荐阅读
- android - 捕获图像后,我的整个片段被重新创建并在数据片段中
- javascript - Laravel HTML Jquery 通过选择图像输入总是返回最高值?
- android - android.support.design.widget.CoordinatorLayout 中的 RelativeLayout 未在 android 版本 8.1 三星 Galaxy J7 Prime 中显示
- jenkins - How to use conditions in Jenkins declarative pipeline "options" block?
- struct - Arduino 结构中的字段未更新
- typescript - 如何在 ReactTS 中导出带有子组件的组件?
- regex - 使用 AHK 正则表达式匹配提取子字符串
- powershell - 直接查询模式的基于事件的调度
- sql - 删除空值并修复对齐
- json - 如何区分传递给视图的 JSON 消息?