【发布时间】:2022-12-22 07:40:06
【问题描述】:
这是我一直在努力的示例代码。 假设我有一个带有许多参数的方法和一个带有默认参数 'a' 调用 M 的方法 M1:
void M(int a, string b, double c, bool d)
{
// do something
}
void M1(string b, double c, bool d)
{
M(1,b,c,d);
}
现在我有一个默认值 a = 1 和 b = "ss" 的方法 M2。 我是否应该像这样使用默认值直接调用 M(我更喜欢这样,因为它似乎避免了一次方法调用,如果我错了请纠正我)
void M2(double c, bool d)
{
M(1,"ss",c,d);
}
或者我应该打电话给 M1 吗?
void M2(double c, bool d)
{
M1("ss",c,d);
}
我更喜欢第一种方法,但是当我查看一些 Microsoft 的源代码时,他们似乎更喜欢第二种方法。 Asp.NetCore DependencyInjection 源代码:
public static IServiceCollection AddSingleton(
this IServiceCollection services,
Type serviceType,
Type implementationType)
{
ThrowHelper.ThrowIfNull(services);
ThrowHelper.ThrowIfNull(serviceType);
ThrowHelper.ThrowIfNull(implementationType);
return Add(services, serviceType, implementationType, ServiceLifetime.Singleton);
}
public static IServiceCollection AddSingleton(
this IServiceCollection services,
Type serviceType)
{
ThrowHelper.ThrowIfNull(services);
return services.AddSingleton(serviceType, serviceType);
}
public static IServiceCollection AddSingleton<TService>(this IServiceCollection services)
where TService : class
{
ThrowHelper.ThrowIfNull(services);
return services.AddSingleton(typeof(TService));
}
第三个 AddSingleton 调用第二个而不是调用第一个。 为什么不只是(也许使 typeof(TService) 成为一个变量,但你明白了):
public static IServiceCollection AddSingleton<TService>(this IServiceCollection services)
where TService : class
{
ThrowHelper.ThrowIfNull(services);
return services.AddSingleton(typeof(TService), typeof(TService));
}
我见过许多 Microsoft 使用第二种方法的案例,但为什么呢?
【问题讨论】:
-
这两种方法都没有带默认值的参数。它们具有硬编码参数。 DI 方法非常不同——它们做不同的事情,并且类型参数在任何情况下都不是硬编码的。
AddSingleton<TService>中,TService是类型参数,不是具体类型
标签: c# asp.net-core