[英]A collection to save the Actions with type parameter - Cannot convert IEnumerable<dynamic> to IEnumerable<MyEntity>
在 Asp.Net http 中間件的以下 class 中,有一個帶有類型參數的方法( ExportResult<T>(...)
)和一個字典( Exports
)來存儲具有不同類型參數的方法。
public class ExportMiddleware : IMiddleware
{
public Dictionary<string, Func<IEnumerable<dynamic>, string, DataSourceLoadOptionsBase, HttpContext, Task>> Exports =>
new Dictionary<string, Func<IEnumerable<dynamic>, string, DataSourceLoadOptionsBase, HttpContext, Task>>();
public ExportMiddleware()
{
Exports.Add("download1", (IEnumerable<dynamic> source, string format, DataSourceLoadOptionsBase dataOptions, HttpContext context) =>
ExportResult<MyEntity>(source, format, dataOptions, context)); // Error
// Cannot convert IEnumerable<dynamic> to IEnumerable<MyEntity>
}
private async Task ExportResult<T>(IEnumerable<T> source, string format, DataSourceLoadOptionsBase dataOptions, HttpContext context)
{
// ....
// report.DataSource = loadedData.data.Cast<T>();
// ....
}
// Consume the dictionary
public Task InvokeAsync(HttpContext context, RequestDelegate next)
{
// ....
var path = context.Request.Path.ToString();
if (Exports.TryGetValue(path, out var func))
return func(source, format, options, context);
return next(context);
}
Cannot convert IEnumerable<dynamic> to IEnumerable<MyEntity>
on source
的錯誤?dynamic
? (沒有class類型參數) 如果您的代碼知道source
將是IEnumerable<MyEntity>
,則將其轉換為:
Exports.Add("download1", (IEnumerable<dynamic> source, string format, DataSourceLoadOptionsBase dataOptions, HttpContext context) =>
ExportResult((IEnumerable<MyEntity>)source, format, dataOptions, context));
如果您想在示例中使用調用模式,可以將強制轉換移動到您的導出助手中:
private async Task ExportResult<T>(IEnumerable<dynamic> dynamicSource, string format, DataSourceLoadOptionsBase dataOptions, HttpContext context)
{
var source = (IEnumerable<T>)dynamicSource;
如果源實際上是不同類型的IEnumerable<>
,但您碰巧知道其中的所有項目都是T
類型,請改用 LINQ Cast 方法:
private async Task ExportResult<T>(IEnumerable<dynamic> dynamicSource, string format, DataSourceLoadOptionsBase dataOptions, HttpContext context)
{
var source = dynamicSource.Cast<T>();
在任何這些情況下,您可能需要重新考慮dynamic
是否真的是您想要的。 由於IEnumerable<>
是協變的,因此IEnumerable<object>
在您共享的所有代碼中都可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.