PrincipalSearchResult<T> with PrincipalSearcher FindAll, why does T have to be Principal and not UserPrincipal

孤街醉人 提交于 2019-12-23 12:47:04

问题


I'm just curious:

List<string> ADUsers = new List<string>();
using (PrincipalContext principle_context = new PrincipalContext(ContextType.Domain, "MYDOMAIN"))
using (UserPrincipal user_principal = new UserPrincipal(principle_context) { Enabled = true, Name = "*", EmailAddress = "*" })
using (PrincipalSearcher user_searcher = new PrincipalSearcher(user_principal))
using (PrincipalSearchResult<Principal> results = user_searcher.FindAll())
{
    foreach (Principal p in results)
    {
        ADUsers.Add(p.Name + " " + ((UserPrincipal)p).EmailAddress);
    }
}

...is there a way to avoid having to cast my results here? I wanted to do something like:

using (PrincipalSearchResult<UserPrincipal> results = user_searcher.FindAll())

...so that my search result would be of the type I needed it, but it seems the FindAll method only allows using the <Principal> type. Is there a better way?

Thank you.


回答1:


Actually foreach will cast the enumerated values for you so you could do this

foreach (UserPrincipal p in results)
{
    ADUsers.Add(p.Name + " " + p.EmailAddress);
}

assuming that Name is defined within UserPrincipal as well as Principal.




回答2:


You could try adding a Cast. Change

PrincipalSearchResult<Principal> results = user_searcher.FindAll()

to

var results = user_searcher.FindAll().Cast<UserPrincipal>()


来源:https://stackoverflow.com/questions/26679819/principalsearchresultt-with-principalsearcher-findall-why-does-t-have-to-be-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!