c#:如何向函数传递参数键/值

本文关键字:参数 函数 | 更新日期: 2023-09-27 18:11:15

我有一个接受bool值的函数,如下所示:

public void LoadEndPoints(bool mock)
{
}

我可以通过LoadEndpoints(true)或LoadEndpoints(false)调用它,但这可能有点难以理解,因为你需要知道true/false代表什么。是否有一种方法将参数名称和值传递给LoadEndPoints(mock = true)等函数?

c#:如何向函数传递参数键/值

是的!

你可以这样指定参数名:

myObject.LoadEndPoints(mock: true);

进一步阅读

  • 命名参数和可选参数(c#编程指南)
另一种提高代码可读性的方法是使用枚举,如下所示:
public enum LoadOption
{
    Normal,
    Mock
}
public void LoadEndPoints(LoadOption option)
{
    ...
}

那么调用看起来就像这样:

myObject.LoadEndPoints(LoadOption.Mock);

你可以使用'Named arguments',这是c# 4.0的一个特性;因此调用:myObject.LoadEndPoints(mock : true);

如果可读性确实是您最关心的问题,您甚至可以公开两个显式方法,并在内部重用逻辑—类似于:

    public void LoadEndPointsWithoutMock()
    {
        LoadEndPoints(false);
    }
    public void LoadEndPointsByMocking()
    {
        LoadEndPoints(true);
    }
    private void LoadEndPoints(bool mock)
    {
    }

同样,我不会说LoadEndPointsWithoutMock等是很好的方法名。理想情况下,这些名称应该与域名有关。

您可以使用KeyValuePair:

   KeyValuePair kvp = new KeyValuePair(BoolType, BoolValue)

是的,您可以在c#中使用以下语法:

myObject.LoadEndPoints(mock : true);

在VB中:

myObject.LoadEndPoints(mock := true)

使用命名参数。看看这个命名参数和可选参数