2011-11-10 76 views

回答

12

簡單:

foreach (var principal in gp.Members) 
{ 
     // How can I determine if principle is a user or a group?   
    UserPrincipal user = (principal as UserPrincipal); 

    if(user != null) // it's a user! 
    { 
    ...... 
    } 
    else 
    { 
     GroupPrincipal group = (principal as GroupPrincipal); 

     if(group != null) // it's a group 
     { 
      .... 
     } 
    } 
} 

基本上,你只投給你有興趣使用的as關鍵字類型 - 如果該值是null然後投失敗 - 否則它成功了。

當然,另一種選擇是要獲得類型,並檢查它:

foreach (var principal in gp.Members) 
{ 
    Type type = principal.GetType(); 

    if(type == typeof(UserPrincipal)) 
    { 
     ... 
    } 
    else if(type == typeof(GroupPrincipal)) 
    { 
    ..... 
    } 
} 
+0

很不錯的解決方案 - 謝謝! –

+1

或使用'is'運算符(例如,var result = principal是UserPrincipal),它可能在內部執行與其中一個選項類似的操作 –

相關問題