【问题标题】:Syntax to iterate over types for delegates迭代代表类型的语法
【发布时间】:2020-11-02 13:39:12
【问题描述】:

考虑通过IHealthChecksBuilder 添加多项健康检查。

循环和使用相同类型的类的正确语法是什么?

以下结果

c 是一种类型,但用作变量。

如何为委托定义类?

var checks = new List<Tuple<Type, string, HealthStatus, string[]>>()
{
    new Tuple<Type, string, HealthStatus, string[]>(typeof(CustomHealthCheckService), "some_health_check", HealthStatus.Unhealthy, new[] {"tag"}),
    new Tuple<Type, string, HealthStatus, string[]>(typeof(OtherCustomHealthCheckService), "some_other_health_check", HealthStatus.Unhealthy, new[] {"other_tag"})
};

IHealthChecksBuilder builder = services.AddHealthChecks();

foreach (var c in checks)
{
    builder.AddCheck<c.Item1>(c.Item2, c.Item3, c.Item4);
}

【问题讨论】:

  • 为什么不使用List&lt;Action&lt;IHealthChecksBuilder&gt;&gt; 并用builder =&gt; builder.AddCheck&lt;CustomHealthCheckService&gt;("some_health_check", HealthStatus.Unhealthy, new[] {"tag"}) 之类的东西填充它,那么它就是foreach(var c in checks) c(builder);
  • Builder 应该有接受 Type 的非泛型版本。如果没有,那么您就不走运了(仍然可以使用反射,但最好不要使用)。或者使用上面的建议。

标签: c# asp.net delegates


【解决方案1】:

基于原始的 cmets,正确格式化的无疑更清洁的解决方案是:

// passed by the user
List<Action<IHealthChecksBuilder>>? checks = new List<Action<IHealthChecksBuilder>>
{
    builder => builder
        .AddCheck<CustomHealthCheckService>("some_health_check", HealthStatus.Unhealthy, new[] {"tag1"})
        .AddCheck<OtherCustomHealthCheckService>("some_other_health_check", HealthStatus.Unhealthy, new[] {"tag2"})
};

IHealthChecksBuilder builder = services.AddHealthChecks();

foreach (var c in checks)
{
    c(builder);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    相关资源
    最近更新 更多