Is there a better way to express a parameterless lambda than () =>?

后端 未结 4 1080
我寻月下人不归
我寻月下人不归 2020-12-02 17:04

The () seems silly. is there a better way?

For example:

ExternalId.IfNotNullDo(() => ExternalId = ExternalId.Trim());

4条回答
  •  悲哀的现实
    2020-12-02 17:46

    Essentially what you're looking for is the inverse of the ?? null coalescing operator (which is called Nullable.GetValueOrDefault() under the covers) - problem is C# doesn't provide a neat OOTB answer.

    Don't know exactly what you're doing but as you are doing:

    ExternalId.IfNotNullDo(()=>ExternalId=ExternalId.Trim());
    

    you might also find a use for:

    class NullExtensions
    {
        public T DefaultOr( this T that, Func transform)
        {
            return that!=default(T) ? transform(that) : default(T);
        }
    }
    

    which would enable:

    var result = input.DefaultOr( _ => _.Trim());
    

    (in general, I'd be trying to steer away from reusing / mutating variables as you seem to be doing and instead going in an Introduce Explaining Variable / Split Temporary Variable direction i.e., use a new variable rather than value = value.DefaultOr( _ => _.Trim());)

提交回复
热议问题