"null this"是否可以使用扩展方法?

Ear*_*rlz 9 .net c# null extension-methods guid

所以,我真的很喜欢使用扩展方法..也许有点太多了.所以,我会问我最近的享受,以确保我不会走得太远.

场景是我们有一个Guid?传入的变量.如果变量为null或者Guid.Empty,那么我们想要使用不同的Guid.所以,我写了一个扩展方法,让它读成英文:

    internal static Guid OrIfEmpty(this Guid? guid, Guid other)
    {
        if (!guid.HasValue || guid.Value == Guid.Empty)
        {
            return other;
        }
        return guid.Value;
    }
Run Code Online (Sandbox Code Playgroud)

这自动意味着"null this"不会抛出异常.例如,这将工作:

((Guid?)null).OrIfEmpty(other);
Run Code Online (Sandbox Code Playgroud)

如果不使用扩展方法,这是不可能的,在我看来可能会产生误导.但是,它只是如此简洁和干净!所以你怎么看?这是可接受的事情,还是让其他程序员感到困惑?

此外,我确信会有其他情况我会做这样的事情并检查thisnull,但这是我现在最好的例子.

注意:我并不是Guid?特别询问这项业务.我要求更多关于实现的整体模式(有一个扩展方法this可以null)

D S*_*ley 5

如果不使用扩展方法,这是不可能的

当然,只是make是一个常规的静态方法调用(这是所有的扩展方法):

在我看来,可能会产生误导

我同意,因为它看起来像是在实例上调用实例方法null.这可能会更糟:

string s = null;
string n = s.OrIfEmpty("empty");
Run Code Online (Sandbox Code Playgroud)

乍一看,这看起来很明显NullReferenceException等待发生,但它编译并按设计工作.

因为你的问题实际上只是征求意见,所以没有一个正确的答案,但我当然会谨慎并记录扩展方法,以表明this参数可以null.或者(正如@quezalcoatl暗示的那样)将其重命名为更明确它支持null值:

internal static Guid OrIfNullOrEmpty(this Guid? guid, Guid other)
Run Code Online (Sandbox Code Playgroud)

  • `string.IsNullOrEmptyOrWhitespace`?:)这都是关于正确的命名! (2认同)