简体   繁体   English

“可选”参数,何时重载以及何时使用可为空的类型?

[英]“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.

相关问题 当不能简单地过载时,混合可选参数和参数 - Mixing optional parameters and params when can't simply overload 如何在不使用 Nullable 的情况下使用可选值类型(即结构体)参数<T>在 WebApi 2 中? - How to use optional value type (i.e. struct) parameters without using Nullable<T> in WebApi 2? 为什么C#编译器认为我在使用可空的long时尝试使用sbyte重载? - Why does the C# compiler think I'm trying to use the sbyte overload when using nullable longs? 当类型已经可以分配为Null时,为什么要使用Nullable? - Why use Nullable when the type can be assigned Null already? 可选参数必须是引用类型、可为空类型或声明为可选参数。 参数名称:参数` - An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters` 在为WCF实现接口时,不能使用可选参数 - Can't use optional parameters when implementing an interface for a WCF 跳过并获取可为空/可选参数 - Skip and Take for nullable / optional parameters 泛型:何时使用new()作为类型参数的约束? - Generics: When to use new() as a constraint of Type Parameters? 什么时候可以为空不能为空? - When is a nullable not a nullable? 当想要启用可为空的引用类型时,如何处理可选的 arguments? - How to deal with optional arguments when wanting to enable nullable reference types?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM