检查空对象和属性

时间:2016-09-08 16:24:05

标签: c#

我在运行下面的代码时遇到此错误。在尝试使用它们之前,我只是想确保对象及其属性不为空。

描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。

private ISharedDatabase CreateSharedDatabase()
{
    var database = new xxxx.Entity.Shared.SharedEntityDatabase("xxDb");
    var user = Container.Instance.Get<IUserContext>();

    **if (user != null && user.Name != null)**
    {
        var name = string.Format("{0} {1}", user.Name.First, user.Name.Last);
        database.SetUserContext(name);
    }

    return database;
}

我尝试了这个并且它不起作用

    if (user != null   )
    {
        **if (user.Name != null)**
        {
            var name = string.Format("{0} {1}", user.Name.First, user.Name.Last);
            database.SetUserContext(name);
        }
    }

这里是Name属性的定义

public class Name
{
    public static bool FirstNameRequired;
    public static bool LastNameRequired;
    public static bool MiddleNameRequired;
    public static string NameExpression;
    public static int NameMaxLength;
    public static int SuffixMaxLength;
    public static bool SuffixRequired;

    public Name();
    public Name(Name value);
    public Name(string name);
    public Name(string firstName, string lastName);
    public Name(string firstName, string middleName, string lastName);
    public Name(string firstName, string middleName, string lastName, string suffix);

    public static Name Empty { get; }
    public string First { get; set; }
    public string Last { get; set; }
    public string Middle { get; set; }
    public string Suffix { get; set; }

    public static Name Parse(string name);
    public static bool TryParse(string value, out Name name);
    public override bool Equals(object obj);
    public override int GetHashCode();
    public override string ToString();
    public string ToString(string format);

    public static bool operator ==(Name n1, Name n2);
    public static bool operator !=(Name n1, Name n2);

    public static implicit operator string(Name value);
    public static implicit operator Name(string value);
}

这是我最终做的事情

    if (user != null )
    {
        var first = user.Name?.First ?? "";
        var last = user.Name?.Last ?? "";

        var name = string.Format("{0} {1}", first, last);
        context.SetUserContext(name);

    }

0 个答案:

没有答案