c# - 在 C# 中进行空检查的更简洁方法?

标签 c# .net-4.0 null .net-4.5

<分区>

假设,我有这个界面,

interface IContact
{
    IAddress address { get; set; }
}

interface IAddress
{
    string city { get; set; }
}

class Person : IPerson
{
    public IContact contact { get; set; }
}

class test
{
    private test()
    {
        var person = new Person();
        if (person.contact.address.city != null)
        {
            //this will never work if contact is itself null?
        }
    }
}

Person.Contact.Address.City != null(这用于检查 City 是否为 null。)

但是,如果 Address 或 Contact 或 Person 本身为 null,则此检查失败。

目前,我能想到的一种解决方案是:

if (Person != null && Person.Contact!=null && Person.Contact.Address!= null && Person.Contact.Address.City != null)

{ 
    // Do some stuff here..
}

有没有更简洁的方法来做到这一点?

我真的不喜欢 null 检查作为 (something == null) 完成。相反,是否有另一种很好的方法来执行类似 something.IsNull() 方法的操作?

最佳答案

在一般情况下,您可以使用表达式树并使用扩展方法进行检查:

if (!person.IsNull(p => p.contact.address.city))
{
    //Nothing is null
}

完整代码:

public class IsNullVisitor : ExpressionVisitor
{
    public bool IsNull { get; private set; }
    public object CurrentObject { get; set; }

    protected override Expression VisitMember(MemberExpression node)
    {
        base.VisitMember(node);
        if (CheckNull())
        {
            return node;
        }

        var member = (PropertyInfo)node.Member;
        CurrentObject = member.GetValue(CurrentObject,null);
        CheckNull();
        return node;
    }

    private bool CheckNull()
    {
        if (CurrentObject == null)
        {
            IsNull = true;
        }
        return IsNull;
    }
}

public static class Helper
{
    public static bool IsNull<T>(this T root,Expression<Func<T, object>> getter)
    {
        var visitor = new IsNullVisitor();
        visitor.CurrentObject = root;
        visitor.Visit(getter);
        return visitor.IsNull;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person nullPerson = null;
        var isNull_0 = nullPerson.IsNull(p => p.contact.address.city);
        var isNull_1 = new Person().IsNull(p => p.contact.address.city);
        var isNull_2 = new Person { contact = new Contact() }.IsNull(p => p.contact.address.city);
        var isNull_3 =  new Person { contact = new Contact { address = new Address() } }.IsNull(p => p.contact.address.city);
        var notnull = new Person { contact = new Contact { address = new Address { city = "LONDON" } } }.IsNull(p => p.contact.address.city);
    }
}

关于c# - 在 C# 中进行空检查的更简洁方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17672481/

相关文章:

wpf - 每次击键而不是在用户输入结束时都调用转换器

c# - Dapper 错误将 tinyint 解析为短?

iphone - iOS:为什么我不能将 nil 设置为 NSDictionary 值?

json - mongoimport 空字段错误

java - 与其他工具相比,从 Java 中的 BufferedImage 获取的 RGB 值不正确

c# - 如何在XAML中将DataBinding设置为任意属性?

c# - 在没有任何窗口的情况下在后台静默运行进程

c# - unity 序列化字典 `Index Out Of Range` 后12项

.net-4.0 - c++/cli 自定义异常 - 标准构造函数

java - 将变量设置为 null 是否只清除引用?