質問

I have this method

public Sorting(Expression<Func<T, object>> property, bool ascending = true)

and I want to be able to call it something like this

public Sorting(null)

By this I mean I want to specify no expression and use the default value for ascending.

How do I do this?

役に立ちましたか?

解決

If you do not need to specify expression, then create overload for this constructor (I think its constructor, not simple method) which don't have expression parameter (instead of passing null):

public Sorting(Expression<Func<T, object>> property, bool ascending = true)
public Sorting(bool ascending = true)

Side note - I also don't like passing boolean values to methods, because they are not expressive and its hard to understand what they mean:

Sorting(false) // what is that?

Usually I create different methods instead (like OrderBy and OrderByDescending) or pass some enumeration (like Order.Ascending and Order.Descending). With constructors you cannot specify custom name, so I use static creation methods for that. That is much easier to read:

Sorting.CreateDescendingSorting()
Sorting(Order.Ascending)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top