[英]“Optional” parameters, when to overload and when to use a nullable type?
由于使类型为可空类型实际上使变量“可选”,我想知道何时在方法参数中使用可空类型以使它们在使用重载时为可选状态是否可以实现相同的目的?
I wouldn't - you'll end up with a lot of null, null, null
. 我不会-您最终会得到很多
null, null, null
。 In C# 4.0 you have optional parameters and named arguments; 在C#4.0中,您具有可选参数和命名参数。 wait a few more months and consider using them.
再等几个月,然后考虑使用它们。 Until then, overloads, or pass it objects that represent the args:
在此之前,重载或传递代表args的对象:
SearchOptions options = new SearchOptions {
Key = 123, Name = "abc"
// but 27 other properties we **haven't** set
}
Search(options);
You would still have to explicitly include a null as a parameter so it's not really optional. 您仍然必须显式包含null作为参数,因此它并不是真正可选的。 It's just annoying, overloading is by far the best approach imo.
只是令人讨厌,重载是迄今为止imo的最佳方法。
I've created some methods that interact with a database where it is just easier to use a nullable type. 我创建了一些与数据库交互的方法,在该数据库中使用空值类型更容易。 If you have a stored procedure to which you're passing arguments, the code will look almost the same if you had two overloaded versions of an insert method, for example.
如果您要向其传递参数的存储过程,例如,如果您有两个重载版本的insert方法,则代码看起来几乎相同。 Using nullable types allows you to avoid repeating yourself across the overloads.
使用可为空的类型可以避免在重载中重复自己。
Edit: If you prefer to use overloading and still want to not repeat code, you could also have an internal function do the work and use the overloads for the public methods. 编辑:如果您更喜欢使用重载并且仍然不想重复代码,则还可以使用内部函数来完成工作并将重载用于公共方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.