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

C#方法调用中参数列表的:语法是什么?名称与作用解析

问题

在浏览.NET源码时,我遇到了如下方法实现,其中调用EqualStartingCharacterCount()方法时使用了ignoreCase: ignoreCase的语法,另有一处调用GetDirectories方法时使用了enumerationOptions: EnumerationOptions.Compatible的语法。请问参数列表中的:有什么作用?该语法的名称是什么?

相关代码如下:

internal static int GetCommonPathLength(string first, string second, bool ignoreCase)
{
    int commonChars = EqualStartingCharacterCount(first, second, ignoreCase: ignoreCase);

    // If nothing matches
    if (commonChars == 0)
        return commonChars;

    // Or we're a full string and equal length or match to a separator
    if (commonChars == first.Length
        && (commonChars == second.Length || IsDirectorySeparator(second[commonChars])))
                return commonChars;

    if (commonChars == second.Length && IsDirectorySeparator(first[commonChars]))
        return commonChars;

    // It's possible we matched somewhere in the middle of a segment e.g. C:\Foodie and C:\Foobar.
    while (commonChars > 0 && !IsDirectorySeparator(first[commonChars - 1]))
                commonChars--;

    return commonChars;
}

另一示例代码:

public static string[] GetDirectories(string path) => GetDirectories(path, "*", enumerationOptions: EnumerationOptions.Compatible);

回答

这个语法叫做命名参数(Named Arguments),是C# 4.0及以后版本引入的特性,参数列表中的:用于将实参和方法定义中对应的形参名称绑定,核心作用如下:

  • 提升代码可读性:直接通过形参名称明确传参含义,无需查阅方法定义就能知道每个参数的作用。比如示例中ignoreCase: ignoreCase,一眼就能看出这个参数是控制比较时是否忽略大小写;enumerationOptions: EnumerationOptions.Compatible则明确指定了枚举目录的选项为兼容模式。
  • 避免位置传参错误:当方法有多个同类型或顺序易混淆的参数时,用命名参数可以彻底规避因参数顺序写错导致的逻辑错误,哪怕后续方法的参数顺序发生调整,只要形参名称不变,代码依然能正常运行。
  • 灵活处理可选参数:如果方法包含可选参数,使用命名参数可以跳过前面的可选参数,直接为后面的参数赋值,无需为前面的可选参数传入默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 07:47:15