NullReferenceexception未被用户代码C#处理

时间:2013-11-05 16:31:46

标签: c# nullreferenceexception

我仍在学习使用C#编程并在办公室中处理项目

public static void SetIdentity(string subId)
{
    if (Proxy.ClientCredentials != null)
    {
        Proxy.ClientCredentials.UserName.UserName = subId;// 
        Proxy.ClientCredentials.UserName.Password = subId;
    }

    ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(customXertificateation);
}

这是我得到此例外的地方:NullReferenceException was unhandled by user code

有人可以看看,并告诉我这里可能有什么问题吗?

2 个答案:

答案 0 :(得分:0)

您可能想要检查UserName是否也为空

public static void SetIdentity(string subId)
{
    if (null != Proxy.ClientCredentials && null != Proxy.ClientCredentials.Username)
    {
        Proxy.ClientCredentials.UserName.UserName = subId;// 
        Proxy.ClientCredentials.UserName.Password = subId;
    }

    ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(customXertificateation);
}

答案 1 :(得分:0)

检查以确保UserName对象的Proxy.ClientCredentials成员也不为空。像这样:

public static void SetIdentity(string subId)
{
    if (Proxy.ClientCredentials != null && Proxy.ClientCredentials.UserName != null)
    {
        Proxy.ClientCredentials.UserName.UserName = subId;// 
        Proxy.ClientCredentials.UserName.Password = subId;
    }

    ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(customXertificateation);
}