[英]C#: How to pass parameter key/values to a function?
I have a function that takes in a bool, shown below: 我有一个带布尔值的函数,如下所示:
public void LoadEndPoints(bool mock)
{
}
I can call this via LoadEndpoints(true) or LoadEndpoints(false), but this can be a bit hard to understand, as you need to know what true/false represents. 我可以通过LoadEndpoints(true)或LoadEndpoints(false)来调用它,但这可能有点难以理解,因为您需要知道true / false代表什么。 Is there a way to pass the parameter name and value to a function such as LoadEndPoints(mock = true)?
有没有办法将参数名称和值传递给诸如LoadEndPoints(mock = true)的函数?
Yes! 是!
You can specify the parameter names like this: 您可以像这样指定参数名称:
myObject.LoadEndPoints(mock: true);
Further Reading 进一步阅读
Another way to improve readability of your code would be to use an enum, like this: 提高代码可读性的另一种方法是使用枚举,如下所示:
public enum LoadOption
{
Normal,
Mock
}
public void LoadEndPoints(LoadOption option)
{
...
}
Then the call would look a bit like this: 然后,调用将看起来像这样:
myObject.LoadEndPoints(LoadOption.Mock);
You could use 'Named arguments', a C# 4.0 feature; 您可以使用C#4.0功能“命名实参”; and thus call:
myObject.LoadEndPoints(mock : true);
因此调用:
myObject.LoadEndPoints(mock : true);
If readability is indeed your prime concern, you could even expose two explicit methods, and internally reuse the logic - something similar to: 如果确实要考虑可读性,那么您甚至可以公开两个显式方法,并在内部重用该逻辑-类似于:
public void LoadEndPointsWithoutMock()
{
LoadEndPoints(false);
}
public void LoadEndPointsByMocking()
{
LoadEndPoints(true);
}
private void LoadEndPoints(bool mock)
{
}
Also, I wouldn't say that LoadEndPointsWithoutMock
, etc. are great method names. 另外,我不会说
LoadEndPointsWithoutMock
等是很好的方法名称。 Ideally, the names should have something to do with the domain. 理想情况下,名称应与域有关。
您可以使用KeyValuePair:
KeyValuePair kvp = new KeyValuePair(BoolType, BoolValue)
Yes, you can do it with the following syntax in c#: 是的,您可以使用c#中的以下语法来实现:
myObject.LoadEndPoints(mock : true);
And in VB: 在VB中:
myObject.LoadEndPoints(mock := true)
Use named parameters. 使用命名参数。 Have a look at this Named and Optional Arguments
看看这个命名和可选参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.