I have this class
public class FilterQuery
{
public FilterQuery() { }
public string OrderBy { set开发者_运维百科; get; }
public string OrderType { set; get; }
public int? Page { set; get; }
public int ResultNumber { set; get; }
}
I would like to use it like this
public IQueryable<Listing> FindAll(FilterQuery? filterQuery)
Is this possible?
This immediately begs the question of why. Classes are by definition reference types and thus are already nullable. It makes no sense to wrap them in a nullable type.
In your case, you can simply define:
public IQueryable<Listing> FindAll(FilterQuery filterQuery)
and call FindAll(null)
to pass no filter query.
If you're using C#/.NET 4.0, a nice option is:
public IQueryable<Listing> FindAll(FilterQuery filterQuery = null)
which means you don't even have to specify the null. An overload would do the same trick in previous versions.
Edit: Per request, the overload would simply look like:
public IQueryable<Listing> FindAll()
{
return FindAll(null);
}
There's no need to do that; all class
types are reference types, which means that it is nullable by definition. Indeed, there is no way to enforce that it's non-null at compile time.
The Nullable<T>
struct is designed to allow value types (which are, by definition, not null) to represent a null value.
It's also worth noting that the ability to compare Nullable<T>
with null
(or Nothing
in VB.NET) is syntactic sugar; because Nullable<T>
is a struct, it cannot actually be null
. In the case where it represents a null value, HasValue
is false
and Value
is default(T)
.
精彩评论