You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重构C#服务注册方法:将单前缀参数改为字符串数组

Refactored C# Method for Multiple Prefix Filtering

Let's adjust the method to support multiple prefixes and update the filtering logic accordingly. Here's the cleaned-up, refactored code:

private void RegisterServices(IServiceCollection serviceCollection, Container container, string[] solutionPrefixes) 
{ 
    // Optional guard clause to avoid unexpected behavior with empty/null input
    if (solutionPrefixes == null || solutionPrefixes.Length == 0)
    {
        throw new ArgumentException("You must provide at least one solution prefix.", nameof(solutionPrefixes));
        // Alternatively, return early or include all assemblies if that's your intended behavior
    }

    var types = AppDomain.CurrentDomain.GetAssemblies() 
        .Where(a => solutionPrefixes.Any(prefix => a.FullName?.StartsWith(prefix) ?? false)) 
        .SelectMany(x => x.GetTypes()) 
        .Where(x => !x.IsAbstract && !x.IsGenericTypeDefinition); 
    // Rest of your registration logic... 
}

Key Changes Breakdown:

  • Parameter Update: Swapped the single string solutionPrefix parameter for a string[] solutionPrefixes to accept multiple prefix values.
  • Null-Safe Filtering: Used a.FullName?.StartsWith(prefix) ?? false to handle edge cases where an assembly's FullName might be null (prevents NullReferenceException and excludes those assemblies).
  • Multiple Prefix Check: Replaced the single prefix match with solutionPrefixes.Any(...) to include assemblies that start with any of the provided prefixes.
  • Guard Clause: Added a check to catch null/empty prefix arrays early—this prevents silent failures where no assemblies would be filtered (since Any() on an empty array returns false).

Optional Adjustments:

  • Case-Insensitive Matching: If you need to ignore case when checking prefixes, modify the StartsWith call:
    a.FullName?.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ?? false
    
  • Allow Empty Prefixes: If an empty array should mean "include all assemblies", adjust the Where clause:
    .Where(a => solutionPrefixes.Length == 0 || solutionPrefixes.Any(prefix => a.FullName?.StartsWith(prefix) ?? false))
    
  • Skip Empty Prefix Entries: To ignore null/empty strings in the prefix array:
    .Where(a => solutionPrefixes.Where(p => !string.IsNullOrEmpty(p)).Any(prefix => a.FullName?.StartsWith(prefix) ?? false))
    

内容的提问来源于stack exchange,提问作者Milad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:05:32