2016-05-20 37 views
0

下面的共享点代码片试图列出所有用户简档属性以及它们的值C#检查,如果对象为空 - 怪异结果

class Program 
{ 
    static void Main(string[] args) 
    { 
     using (SPSite site = new SPSite(args[0], SPUserToken.SystemAccount)) 
     { 

      var profileManager = new UserProfileManager(SPServiceContext.GetContext(site)); 
      UserProfile userProfile = profileManager.GetUserProfile(args[1]); 

      foreach (var Property in userProfile.Properties) 
      { 
       Console.WriteLine("Property DisplayName = " + Property.DisplayName + "; " + "Property Name = " + Property.Name); 
       if (userProfile[Property.Name] != null) 
       { 
        Console.WriteLine("user profile property value " + Property.Name + " is not null"); 
        Console.WriteLine("property Value = " + userProfile[Property.Name].ToString()); 
       } 
       else 
       { 
        Console.WriteLine("property Value = null"); 
       } 
      } 
     } 
    } 
} 

这将产生以下输出:

output

这表明该异常被它试图检查用户配置文件属性值为空行来

if (userProfile[Property.Name] != null) 

但我已经把它与null比较。那么为什么它应该给出对象为空的错误呢?

有人可以请澄清一下吗?

userProfile不为null,Property.Name也不为空,我检查userProfile [Property.Name]!= null。但它随着错误而爆发。 究竟是怎么回事?

+2

我没有加载在SharePoint的引用,但它会看到,USERPROFILE索引功能在内部抛出一个空异常前的相比,函数的结果是你的,如果为空发声明。 –

+1

也许该特定'Property'的'Name'属性是'null'。 –

+1

您确定您的PDB文件正在重建,并且堆栈跟踪是最新的? – Mikanikal

回答

1

您假定userProfile [Property.Name] .Value不为null。试试这个

if (userProfile[Property.Name] != null 
     && userProfile[Property.Name].Value != null) 
    { 
     Console.WriteLine("property Value = " + userProfile[Property.Name].Value.ToString()); 
    } 
+0

从更新的代码和输出,很显然,这行错误发生在这一行Console.WriteLine(“属性值=”+ userProfile [Property.Name] .ToString());好像ToString()实现像你所说的那样显示Value对象 –

0

在这一行:

if (userProfile[Property.Name] != null) 

Property为空,试图从一个空值获得.Name将抛出NullReferenceException

+0

Thang编码器时发生错误,如果查看错误发生在Property.Name正上方的那一行,则会打印 –

+0

Can你请更新你的问题来显示整个堆栈跟踪?谢谢 –