问题
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