【问题标题】:Should all my methods call one signle method with many parameters? [closed]我的所有方法都应该调用一个带有多个参数的方法吗? [关闭]
【发布时间】: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));
}

链接:https://source.dot.net/#Microsoft.Extensions.DependencyInjection.Abstractions/ServiceCollectionServiceExtensions.cs,55d44dc023165db2

第三个 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&lt;TService&gt;中,TService是类型参数,不是具体类型

标签: c# asp.net-core


【解决方案1】:

使用默认参数有更好的方法,你可以这样实现。和你可以用它来满足你的其他要求一样。

void M(string b, double c, bool d, int a = 1)
{
            
}

void M1(string b, double c, bool d)
{
    M(b, c, d);
}

Here 是官方文档。

【讨论】:

  • 在那种情况下,不再需要 M1,因为 M1(b,c,d) == M2(b,c,d)
猜你喜欢
  • 2015-06-24
  • 2015-12-28
  • 1970-01-01
  • 2023-03-24
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多