Nullable class?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-23 16:34:40

问题


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?


回答1:


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);
}



回答2:


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).



来源:https://stackoverflow.com/questions/3132667/nullable-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!